package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.GsonBuilder;
import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.service.MoldMaterialService;
import com.wonder.app.service.SyncKingdeeOrderService;
import com.wonder.bean.kingdee.KingdeeAccount;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.exception.CustomException;
import com.wonder.common.utils.DateUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import org.terracotta.quartz.TerracottaJobStore;
import org.yaml.snakeyaml.events.Event;

import javax.print.DocFlavor;
import java.beans.FeatureDescriptor;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SyncKingdeeOrderServiceImpl implements SyncKingdeeOrderService {
    /**
     * Logger
     */
    private static final Logger _logger = LoggerFactory.getLogger(PurInServiceImpl.class);
    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;


    @Autowired
    private StkApplyDao stkApplyDao;

    @Autowired
    private StkApplyDetailDao stkApplyDetailDao;

    @Autowired
    private PurInDao purInDao;

    @Autowired
    private ReceiveDao receiveDao;

    @Autowired
    private ReceivedetailDao receivedetailDao;

    @Autowired
    private StkweightDao stkweightDao;

    @Autowired
    private StkTransferAppDetailDao stkTransferAppDetailDao;

    @Autowired
    private StkTransferAppDao stkTransferAppDao;

    @Autowired
    private PpBomDao ppBomDao;

    @Autowired
    private TrayDao trayDao;

    @Autowired
    private PrdPickDao prdPickDao;
    @Autowired
    private QingPurInDao qingPurInDao;

    @Autowired
    private MoldMaterialService moldMaterialService;

    @Autowired
    private SfcProplanDao sfcProplanDao;

    @Autowired
    private PickDetailDao pickDetailDao;


    @Autowired
    private MoldMaterialDao moldMaterialDao;

    @Autowired
    private SfcOptrptDao sfcOptrptDao;

    @Autowired
    private SfcOptrptDetailDao sfcOptrptDetailDao;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;

    @Override
    public void syncPurInOrder(Long user_id, String userName, PurIn purIn, List<PurInDetail> detailList, String customAuditDateTime) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请维护");
        }

        Map<String, Object> dataMap = new HashMap<>();//key:收料单号，val:入库详情集合
        for (PurInDetail purInDetail : detailList) {
            String receiveBillNo = purInDetail.getReceiveBillNo();
            List<PurInDetail> mapDetail = VtuzxUtil.getObject(dataMap, receiveBillNo);
            if (!VtuzxUtil.isEmpty(mapDetail)) {//如果当前已经有数据
                mapDetail.add(purInDetail);
                dataMap.put(receiveBillNo, mapDetail);
            } else {//如果当前没有数据
                List<PurInDetail> dataList = new ArrayList<>();
                dataList.add(purInDetail);
                dataMap.put(receiveBillNo, dataList);
            }
        }
        //循环map集合，根据收料通知单号分组传金蝶
        for (Map.Entry entry : dataMap.entrySet()) {
            String receiveBillNo = (String) entry.getKey();

            List<PurInDetail> dataList = (List<PurInDetail>) entry.getValue();
            Map<String, Object> model = new LinkedHashMap<>();//采购入库api总参
            //根据收料通知单号查询金蝶fid和fentryid,用于linked采购入库单
            Receive receive = receiveDao.selectOne(new LambdaQueryWrapper<Receive>()
                    .eq(Receive::getBillNo, receiveBillNo));
            //查询收料通知单号获取结算方式结算币别等信息
            Map<String, Object> receiveMap = recceiveQuery(client, receiveBillNo);
            String settleMode = VtuzxUtil.getString(receiveMap, "settleMode");//结算方式
            String FSettleCurrId = VtuzxUtil.getString(receiveMap, "FSettleCurrId");//结算币别
            String FPayConditionId = VtuzxUtil.getString(receiveMap, "FPayConditionId");//付款条件
            String FPurDeptId = VtuzxUtil.getString(receiveMap, "FPurDeptId");//采购部门
            String FPurchaserId = VtuzxUtil.getString(receiveMap, "FPurchaserId");//采购员
            Double FExchangeRate = VtuzxUtil.getDouble(receiveMap, "FExchangeRate");//汇率

            List<Map<String, Object>> FInStockEntry = new ArrayList<>();//采购入库体数据
            for (PurInDetail detail : dataList) {
                String materialNo = detail.getMaterialNo();
                Boolean isLocation = detail.getIsLocation();//是否启用仓位
                //查询物料是否有辅助单位
                String auxNo = checkFAux(materialNo, client);

                //根据收料单号和物料编码查询收料明细获取单价
//                Receivedetail receivedetail1 = receivedetailDao.selectOne(new LambdaQueryWrapper<Receivedetail>()
//                        .eq(Receivedetail::getBillNo, receiveBillNo)
//                        .eq(Receivedetail::getMaterialNumber, materialNo));
                Receivedetail receivedetail1 = receivedetailDao.selectOne(new LambdaQueryWrapper<Receivedetail>()
                        .eq(Receivedetail::getId,detail.getReveiveId()));
                Map<String, Object> colMap = new LinkedHashMap<>();
                colMap.put("FRowType", "Standard");//产品类型
                colMap.put("FMaterialId", new Document("FNumber", detail.getMaterialNo()));//物料编码
                colMap.put("FUnitID", new Document("FNumber", detail.getUnitNo()));//物料单位
                if (!VtuzxUtil.isEmpty(auxNo)) {
                    colMap.put("FAuxUnitID", new Document("FNumber", auxNo));//辅助单位
                }
                colMap.put("FPOOrderNo", receive.getPurOrderNo());//订单单号，通过linked方式无法获取，直接传
                colMap.put("FMustQty", detail.getRealQty());//实收数量
                colMap.put("FRealQty", detail.getRealQty());//实收数量
                colMap.put("FPriceUnitID", new Document("FNumber", detail.getUnitNo()));//计价单位
                colMap.put("FLot", new Document("FNumber", detail.getFlot()));//批号
                colMap.put("FStockId", new Document("FNumber", detail.getStockNo()));//仓库
                if (isLocation) {
                    colMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber", detail.getLocationNo())));//仓位
                }

                colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                colMap.put("FTaxPrice", receivedetail1.getFPrice());//含税单价
                colMap.put("FGiveAway", false);//是否正品
                colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
                colMap.put("FCheckInComing", false);//来料校验
                colMap.put("FIsReceiveUpdateStock", false);//收料后更新库存状态
                colMap.put("FPriceBaseQty", detail.getRealQty());//计价基本数量
                colMap.put("FRemainInStockUnitId", new Document("FNumber", detail.getUnitNo()));//采购单位
                colMap.put("FBILLINGCLOSE", false);//立账关闭
                colMap.put("FRemainInStockQty", detail.getRealQty());//采购数量
                colMap.put("FAPNotJoinQty", detail.getRealQty());//未关联应付数量（计价单位
                colMap.put("FRemainInStockBaseQty", detail.getRealQty());//采购基本数量
                colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
                colMap.put("FSRCBILLTYPEID", "PUR_ReceiveBill");//原单类型
                colMap.put("FSRCBillNo", receiveBillNo);//原单类型
                //添加linked信息(收料通知单关联)
                List<Map<String, Object>> linkList = new ArrayList<>();
                Map<String, Object> linkMap = new LinkedHashMap<>();
                linkMap.put("FInStockEntry_Link_FRULEID", "PUR_ReceiveBill-STK_InStock");//下推规则
                linkMap.put("FInStockEntry_Link_FSTABLENAME", "T_PUR_ReceiveEntry");//关联表名
                linkMap.put("FInStockEntry_Link_FSBILLID", receive.getFID());//源单内码，同步收料通知单时将fid和fentryid同步到中台
                linkMap.put("FInStockEntry_Link_FSID", receivedetail1.getFEntryId());// 源单分录内码
                linkList.add(linkMap);
                colMap.put("FInStockEntry_Link", linkList);
                FInStockEntry.add(colMap);
            }

            model.put("FID", 0);//实体主键
            model.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型标准采购入库单
            model.put("FSettleTypeId", new Document("FNUMBER", settleMode));//结算方式
            //单据日期如果定义用自定义的日期，没有的话按照审核日期
            if (!VtuzxUtil.isEmpty(customAuditDateTime)) {
                model.put("FDate", customAuditDateTime);//入库日期
            } else {
                model.put("FDate", DateUtils.dateToStr(purIn.getAuditTime(), "yyyy-MM-dd HH:mm:ss"));//入库日期
            }
            model.put("FStockOrgId", new Document("FNumber", "100"));//收料组织
            model.put("FDemandOrgId", new Document("FNumber", "100"));//需求组织
            model.put("FPurchaseOrgId", new Document("FNumber", "100"));//采购组织
            model.put("FSupplierId", new Document("FNumber", purIn.getSupplierNo()));//供应商
            model.put("FPurchaseDeptId", new Document("FNumber", FPurDeptId));//采购部门
            model.put("FPurchaserId", new Document("FNumber", FPurchaserId));//采购员
            model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
            model.put("FOwnerIdHead", new Document("FNumber", "100"));//货主
            model.put("F_VKFP_lljyd", purIn.getInspectBillNo());//来料检验单号
            model.put("F_PSUH_TEXT_9Z6", purIn.getBillNo());//中台采购入库单号

            Document FInStockFin = new Document();
            FInStockFin.append("FSettleOrgId", new Document("FSettleOrgId", new Document("FNumber", "100")));
            FInStockFin.append("FSettleCurrId", new Document("FNumber", FSettleCurrId));//结算币别
            FInStockFin.append("FPayConditionId", new Document("FNumber", FPayConditionId));//付款条件
            FInStockFin.append("FExchangeRate", FExchangeRate);
            model.put("FInStockFin", FInStockFin);//财务信息
            model.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
            model.put("FInStockEntry", FInStockEntry);

            Map<String, Object> kneeParam = new LinkedHashMap<>();
            kneeParam.put("NeedUpDateFields", new ArrayList<>());
            kneeParam.put("NeedReturnFields", new ArrayList<>());
            kneeParam.put("IsDeleteEntry", true);
            kneeParam.put("SubSystemId", "");
            kneeParam.put("IsVerifyBaseDataField", true);
            kneeParam.put("IsEntryBatchFill", false);
            kneeParam.put("ValidateFlag", true);
            kneeParam.put("NumberSearch", true);
            kneeParam.put("InterationFlags", "");
            kneeParam.put("Model", model);
            try {
                List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "STK_InStock", kneeParam);
                VtuzxMap kingdeeCustomerMap = customerList.get(0);
                String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
                vtuzxKingdeeService.submit(client, "STK_InStock", "0", number);
                vtuzxKingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
            } catch (Exception e) {
                _logger.info(e.getMessage());
                throw new RuntimeException(e.getMessage());
            }


        }


    }

    /**
     * 校验物料是否有辅助单位
     *
     * @param materialNo
     * @return
     * @throws Exception
     */
    private String checkFAux(String materialNo, VtuzxKingdeeCloudClient client) throws Exception {

        String auxNo = "";
        List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FAuxUnitID.FNumber"//辅助单位编码
                ),
                String.format("FNumber = '%s'", materialNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(materialQuery)) {
            auxNo = VtuzxUtil.getString(materialQuery.get(0), "FAuxUnitID.FNumber");
        }
        return auxNo;
    }

    private Map<String, Object> recceiveQuery(VtuzxKingdeeCloudClient client, String receiveBillNo) throws Exception {
        //根据收料通知单号查询结算币别和计算方式
        List<VtuzxMap> receiveQuery = vtuzxKingdeeService.query(client, "PUR_ReceiveBill", new VtuzxArrayList<>(
                        "FSettleCurrId.fnumber",//结算币别
                        "FExchangeRate",//汇率
                        "FPayConditionId.fnumber",//付款条件
                        "FPurDeptId.fnumber",//采购部门
                        "FPurchaserId.fnumber",//采购员
                        "FSettleModeId.fnumber"//结算方式
                ),
                String.format("FBillNo = '%s'", receiveBillNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(receiveQuery)) {
            String FSettleCurrId = VtuzxUtil.getString(receiveQuery.get(0), "FSettleCurrId.fnumber");//结算币别
            String settleMode = VtuzxUtil.getString(receiveQuery.get(0), "FSettleModeId.fnumber");//结算方式
            String FPayConditionId = VtuzxUtil.getString(receiveQuery.get(0), "FPayConditionId.fnumber");//付款条件
            String FPurDeptId = VtuzxUtil.getString(receiveQuery.get(0), "FPurDeptId.fnumber");//采购部门
            String FPurchaserId = VtuzxUtil.getString(receiveQuery.get(0), "FPurchaserId.fnumber");//采购员
            Double FExchangeRate = VtuzxUtil.getDouble(receiveQuery.get(0), "FExchangeRate");//汇率
            Map<String, Object> data = new HashMap<>();
            data.put("settleMode", settleMode);
            data.put("FSettleCurrId", FSettleCurrId);
            data.put("FPayConditionId", FPayConditionId);
            data.put("FExchangeRate", FExchangeRate);
            data.put("FPurDeptId", FPurDeptId);
            data.put("FPurchaserId", FPurchaserId);
            return data;
        }
        return new HashMap<>();
    }


    /**
     * 其他入库上传金蝶
     *
     * @param user_id
     * @param userName
     * @param stkOtherIn
     * @param detailList
     * @throws Exception
     */
    public void syncOtherIn(Long user_id, String userName, StkOtherIn stkOtherIn, List<StkOtherInDeatil> detailList) throws Exception {
        Map<String, Object> model = new LinkedHashMap<>();//总参
        model.put("Fid", 0);
        model.put("FDate", VtuzxUtil.formatYmdHmsF(stkOtherIn.getDate()));//单据日期
        model.put("FBillTypeID", new Document("FNUMBER", "QTRKD01_SYS"));//单据类型
        model.put("FStockOrgId", new Document("FStockOrgId", "100"));//库存组织
        model.put("FStockDirect", "GENERAL");//库存方向
        model.put("FDEPTID", new Document("FNUMBER", stkOtherIn.getDeptNumber()));//部门
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型

//        model.put("FBillNo",stkOtherIn.getBillNo());

        List<Map<String, Object>> OtherInEntry = new ArrayList<>();//表体体数据
        for (StkOtherInDeatil deatil : detailList) {
            Map<String, Object> colMap = new LinkedHashMap<>();
            colMap.put("FMATERIALID", new Document("FNumber", deatil.getMaterialNo()));//物料编码
            colMap.put("FUnitID", new Document("FNumber", deatil.getBasicUnitNo()));//单位编码
            colMap.put("FSTOCKID", new Document("FNumber", deatil.getStockNo()));//仓库编码
            colMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber", deatil.getLocationNo())));//仓库编码
            colMap.put("FSTOCKSTATUSID", new Document("FNumber", "KCZT01_SYS"));//库存状态
//            colMap.put("FLOT",new Document("FNumber",deatil.getLot()));//批号
            colMap.put("FQty", deatil.getQty());//实收数量
            colMap.put("FEntryNote", deatil.getNote());//备注
            colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
            colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
            colMap.put("FKEEPERTYPEID", "BD_KeeperOrg");//保管者类型
            colMap.put("FKEEPERID", new Document("FNumber", "100"));//保管者
//            colMap.put("FDate",VtuzxUtil.formatYmdHms(stkOtherIn.getDate()));//日期

            OtherInEntry.add(colMap);

        }
        model.put("FEntity", OtherInEntry);//表体
        //固定参数
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);
        //金蝶登录
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "STK_MISCELLANEOUS", kneeParam);
            //获取返回成功的单据编号
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "STK_MISCELLANEOUS", "0", number);
            vtuzxKingdeeService.audit(client, "STK_MISCELLANEOUS", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
//            _logger.info(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 其他出库上传金蝶
     *
     * @param user_id
     * @param userName
     * @param stkotherout
     * @param detailList
     * @throws Exception
     */
    public void syncOtherOUT(Long user_id, String userName, Stkotherout stkotherout, List<StkOtheroutDetail> detailList) throws Exception {

        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        String weightNo = stkotherout.getWeightNo();//申请单号
        //查询申请单明细，通过linked方式，关联上申请单
        StkApply stkApply = stkApplyDao.selectOne(new LambdaQueryWrapper<StkApply>()
                .eq(StkApply::getFBILLNO, weightNo));
        List<StkApplyDetail> stkApplyDetailList = stkApplyDetailDao.selectList(new LambdaQueryWrapper<StkApplyDetail>()
                .eq(StkApplyDetail::getFID, stkApply.getFID()));


        Map<String, Object> model = new LinkedHashMap<>();//总参
        model.put("Fid", "0");//表头内码
        model.put("FBillTypeID", new Document("FNUMBER", "QTCKD01_SYS"));//单据类型
        model.put("FStockOrgId", new Document("FStockOrgId", "100"));//库存组织
        model.put("FStockDirect", "GENERAL");//库存方向
        model.put("FDate", VtuzxUtil.formatYmdHmsF(stkotherout.getDate()));//出库日期
        model.put("FDeptId", new Document("FNumber", stkotherout.getDeptNumber()));//领料部门
        model.put("FBizType", "0");//业务类型
//        model.put("FNote", stkotherout.getWeightNo());//备注存出库申请单号
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("F_PSUH_Assistant_om1", new Document("FNumber","CKSQLX08_SYS"));//出库申请类型

        List<Map<String, Object>> OtherOutEntry = new ArrayList<>();//表体体数据
        for (StkOtheroutDetail detail : detailList) {
            Map<String, Object> colMap = new LinkedHashMap<>();

            colMap.put("FMaterialId", new Document("FNumber", detail.getMaterialNo()));//物料编码
            colMap.put("FUnitId", new Document("FNumber", detail.getBasicUnitNo()));//物料单位
            colMap.put("FQty", detail.getQty());//实发数量

            colMap.put("FStockId", new Document("FNumber", detail.getStockNo()));//仓库编码
            colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            colMap.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
            colMap.put("FOwnerIdHead", new Document("FNumber", "100"));//货主
            colMap.put("FKeeperTypeId", "BD_KeeperOrg");//保管者类型
            colMap.put("FKeeperId", new Document("FNumber", "100"));//保管者
            colMap.put("FBaseUnitId", new Document("FNumber", detail.getBasicUnitNo()));//基本单位编码
            colMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber",detail.getLocationNo())));//基本单位编码

            //添加linked信息(收料通知单关联)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
//            linkMap.put("FInStockEntry_Link_FRULEID", "200daae8-cab2-4c81-9a89-b290dbf3a034");//下推规则
            linkMap.put("FEntity_Link_FRuleId", "STK_OutStockApplyToSTK_MisDelivery");//下推规则
            linkMap.put("FEntity_Link_FSTABLENAME", "T_STK_OUTSTOCKAPPLYENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBILLID", stkApply.getFID());//源单内码
            linkMap.put("FEntity_Link_FSID", detail.getStkId());// 源单分录内码
            linkList.add(linkMap);
            colMap.put("FEntity_Link", linkList);
            OtherOutEntry.add(colMap);
        }
        model.put("FEntity", OtherOutEntry);

        //固定参数
        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "STK_MisDelivery", kneeParam);
            //获取返回成功的单据编号
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "STK_MisDelivery", "0", number);
            vtuzxKingdeeService.audit(client, "STK_MisDelivery", "0", number, "STK_MisDelivery");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
    }

    @Override
    public void syncPurReturn(Long user_id, String userName, PurReturn purReturn, List<PurReturnDetail> detailList) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        Map<String, Object> purParam = new LinkedHashMap<>();//传单param
        Map<String, Object> purModel = new LinkedHashMap<>();//单据头
        //添加单据头信息
        purModel.put("FID", 0);
        purModel.put("FBillTypeId", new Document("FNUMBER", "TLD01_SYS"));
        purModel.put("FDate", DateUtils.dateToStr(purReturn.getAuditTime(), "yyyy-MM-dd HH:mm:ss"));
        purModel.put("FMRTYPE", "B");//退料类型
        purModel.put("FMRMODE", "A");//退料方式
        purModel.put("FStockOrgId", new Document("FNumber", "100"));//退料组织
        purModel.put("FRequireOrgId", new Document("FNumber", "100"));
        purModel.put("FPurchaseOrgId", new Document("FNumber", "100"));
        purModel.put("FSupplierID", new Document("FNumber", purReturn.getSupplierNo()));//供应商
        purModel.put("FACCEPTORID", new Document("FNumber", purReturn.getSupplierNo()));//接收方
        purModel.put("FSettleId", new Document("FNumber", purReturn.getSupplierNo()));//结算方
        purModel.put("FCHARGEID", new Document("FNumber", purReturn.getSupplierNo()));//收款方
        purModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        purModel.put("FOwnerIdHead", new Document("FNumber", "100"));//货主

        Map<String, Object> purmrbfin = new LinkedHashMap<>();//财务信息
        purmrbfin.put("FSettleOrgId", new Document("FNumber", "100"));//结算组织
        purmrbfin.put("FSettleCurrId", new Document("FNumber", "PRE001"));//结算币别
        purmrbfin.put("FIsIncludedTax", true);
        purmrbfin.put("FPRICETIMEPOINT", "1");
        purmrbfin.put("FLOCALCURRID", new Document("FNumber", "PRE001"));//本位币
        purmrbfin.put("FEXCHANGETYPEID", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        purmrbfin.put("FEXCHANGERATE", 1);//汇率
        purmrbfin.put("FISPRICEEXCLUDETAX", true);//价外税
        purModel.put("FPURMRBFIN", purmrbfin);

        String weightNo = purReturn.getWeightNo();//称重申请单号
        Stkweight stkweight = stkweightDao.selectOne(new LambdaQueryWrapper<Stkweight>()
                .eq(Stkweight::getBillNo, weightNo));
        String purOrderNo = stkweight.getPurOrderNo();//采购订单单号


        String FId = "";//原单内码
        String FEntryId = "";//分录内码
        //根据采购订单号查询原单内码和分录内码
        List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "PUR_PurchaseOrder", new VtuzxArrayList<>(
                        "FId",
                        "FPOOrderEntry_FEntryID"
                ),
                String.format("FBillNo = '%s'", purOrderNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(prdInQuery)) {
            FId = VtuzxUtil.getString(prdInQuery.get(0), "FId");
            FEntryId = VtuzxUtil.getString(prdInQuery.get(0), "FPOOrderEntry_FEntryID");
        }
        List<Map<String, Object>> FPURMRBENTRY = new ArrayList<>();//明细信息
        //添加明细信息
        for (PurReturnDetail detail : detailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FRowType", "Standard");
            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));
//            entryMap.put("FMaterialDesc",new Document("FNumber",materialSpec));
            entryMap.put("FUnitID", new Document("FNumber", detail.getBasicUnitNo()));
            entryMap.put("FRMREALQTY", detail.getInfactQty());//实退数量
            entryMap.put("FREPLENISHQTY", detail.getInfactQty());//补料数量
            entryMap.put("FKEAPAMTQTY", detail.getInfactQty());//扣款数量
            entryMap.put("FPRICEUNITID", new Document("FNumber", detail.getBasicUnitNo()));
            entryMap.put("FSTOCKID", new Document("FNumber", detail.getStockNo()));
            entryMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
            entryMap.put("FIsReceiveUpdateStock", false);
            entryMap.put("FGiveAway", false);
            entryMap.put("FPriceBaseQty", detail.getInfactQty());//扣款数量
            entryMap.put("FCarryUnitId", new Document("FNumber", detail.getBasicUnitNo()));
            entryMap.put("FCarryQty", detail.getInfactQty());
            entryMap.put("FCarryBaseQty", detail.getInfactQty());
            entryMap.put("FBILLINGCLOSE", false);//立账关闭
            entryMap.put("FOWNERTYPEID", "BD_OwnerOrg");
            entryMap.put("FOWNERID", new Document("FNumber", "100"));
            entryMap.put("FENTRYTAXRATE", 13);
            entryMap.put("FIsStock", false);


            //添加link信息(和采购订单关联)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FPURMRBENTRY_Link_FRuleId", "PUR_PurchaseOrder-PUR_MRB");//下推规则
            linkMap.put("FPURMRBENTRY_Link_FSTableName", "t_PUR_POOrderEntry");//关联表名
            linkMap.put("FPURMRBENTRY_Link_FSBillId", FId);//源单内码
            linkMap.put("FPURMRBENTRY_Link_FSId", FEntryId);// 源单分录内码
            linkList.add(linkMap);
            entryMap.put("FPURMRBENTRY_Link", linkList);
            FPURMRBENTRY.add(entryMap);
        }
        purModel.put("FPURMRBENTRY", FPURMRBENTRY);
        purParam.put("NeedUpDateFields", new ArrayList<>());
        purParam.put("NeedReturnFields", new ArrayList<>());
        purParam.put("IsDeleteEntry", true);
        purParam.put("SubSystemId", "");
        purParam.put("IsVerifyBaseDataField", false);
        purParam.put("IsEntryBatchFill", true);
        purParam.put("ValidateFlag", true);
        purParam.put("NumberSearch", true);
        purParam.put("InterationFlags", "");
        purParam.put("Model", purModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PUR_MRB", purParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PUR_MRB", "0", number);
            vtuzxKingdeeService.audit(client, "PUR_MRB", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 销售订单
     *
     * @param saleOrder
     * @param saleOrderDetailList
     * @throws Exception
     */
    public void syncSaleOrder(SaleOrder saleOrder, List<SaleOrderDetail> saleOrderDetailList, Map<String, Object> materialToMap, Map<String, Object> customerMap, Map<String, Object> currencyMap, Long user_id) throws Exception {

        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头
        //查询客户编码
//        String cusNo = getCusNo(saleOrder.getCusTomer());
        String cusNo = VtuzxUtil.getString(customerMap, saleOrder.getCusTomer());
        String FCustNo = VtuzxUtil.getString(customerMap, saleOrder.getFCustId());//结算客户

        //单据头
        saleModel.put("FID", 0);
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSDD01_SYS"));
        saleModel.put("FCustId", new Document("FNUMBER", FCustNo));//客户
        saleModel.put("F_PSUH_Base_qtr", new Document("FNUMBER", cusNo));//终端客户
        saleModel.put("FDate", DateUtils.dateToStr(saleOrder.getInDate(), "yyyy-MM-dd HH:mm:ss"));
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));
        saleModel.put("F_PSUH_Text_qtr", saleOrder.getCusBillNo());
        saleModel.put("F_PSUH_Integer_83g", saleOrder.getWeekNo());

        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息
        //查询币别的编码
        String currency = saleOrderDetailList.get(0).getCurrency();//币别
        String currentyNo = VtuzxUtil.getString(currencyMap, currency);
        if (VtuzxUtil.isEmpty(currentyNo)) {
            throw new RuntimeException(String.format("金蝶不存在币别%s", currency));
        }
//        List<VtuzxMap> currenQuery = vtuzxKingdeeService.query(client, "BD_Currency", new VtuzxArrayList<>(
//                        "FNumber"
//                ),
//                String.format("FName = '%s'", currency),null , 0, 0);
//        if (!VtuzxUtil.isEmpty(currenQuery)) {
//            currentyNo = VtuzxUtil.getString(currenQuery.get(0),"FNumber");
//        } else {
//            throw new RuntimeException(String.format("金蝶不存在币别%s",currency));
//        }
        double FExchangeRate = 1.0;
        //如果是人民币的话不用查税率
        if (!"人民币".equals(currency)) {
            //根据原币查询汇率
            List<VtuzxMap> tateQuery = vtuzxKingdeeService.query(client, "BD_Rate", new VtuzxArrayList<>(
                            "FExchangeRate"
                    ),
                    String.format("FCyForID.fnumber = '%s'", currentyNo), null, 0, 0);
            if (!VtuzxUtil.isEmpty(tateQuery)) {
                FExchangeRate = VtuzxUtil.getDouble(tateQuery.get(0), "FExchangeRate");
            } else {
                throw new RuntimeException(String.format("金蝶不存在原币为%s的汇率", currency));
            }
        }
        saleFIn.put("FSettleCurrId", new Document("FNumber", currentyNo));//结算币别
        saleFIn.put("FExchangeRate", FExchangeRate);//汇率
        saleModel.put("FSaleOrderFinance", saleFIn);

        //订单明细
        List<Map<String, Object>> FSaleOrderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (SaleOrderDetail detail : saleOrderDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            String tyNo = detail.getTyPartNo();//ty件号
            entryMap.put("FRowType", "Standard");
            Map<String, Object> materialMap = VtuzxUtil.getObject(materialToMap, tyNo);
            String unitNo = "";
            if (!VtuzxUtil.isEmpty(materialMap)) {
                unitNo = VtuzxUtil.getString(materialMap, "unitNo");

            }

//            String unitNo = "";
//            String materialNo = "";
//            //根据ty件号(对应金蝶物料编码)查询单位编码
//            List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
//                            "FBaseUnitId.fnumber",
//                            "FNumber"
//                    ),
//                    String.format("FNumber = '%s'", tyNo),null , 0, 0);
//            if (!VtuzxUtil.isEmpty(prdInQuery)) {
//               unitNo = VtuzxUtil.getString(prdInQuery.get(0),"FBaseUnitId.fnumber");
//               materialNo = VtuzxUtil.getString(prdInQuery.get(0),"FNumber");
//            } else {
//                throw new RuntimeException(String.format("金蝶不存在物料%s",tyNo));
//            }
            entryMap.put("FMATERIALID", new Document("FNumber", tyNo));//物料编码
            entryMap.put("FUnitID", new Document("FNumber", unitNo));//单位
            entryMap.put("Fqty", detail.getQty());//销售数量
            entryMap.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
            entryMap.put("FTaxPrice", detail.getTaxPrice());//含税单价
            entryMap.put("FEntryTaxRate", detail.getTaxRate());//税率
            entryMap.put("FDeliveryDate", DateUtils.dateToStr(detail.getDeliveDate(), "yyyy-MM-dd HH:mm:ss"));//交货期
            entryMap.put("F_PSUH_Date_ca9", DateUtils.dateToStr(detail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
            entryMap.put("F_PSUH_Integer_apv", detail.getShipWeek());//船期周数
            entryMap.put("F_PSUH_Integer_tzk", detail.getDeliveWeek());//计划出货周数
            FSaleOrderEntry.add(entryMap);

        }
        saleModel.put("FSaleOrderEntry", FSaleOrderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);


        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "SAL_SaleOrder", saleParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "SAL_SaleOrder", "0", number);
            vtuzxKingdeeService.audit(client, "SAL_SaleOrder", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 查询客户编码
     *
     * @param cusName
     * @return
     * @throws Exception
     */
    private String getCusNo(String cusName) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        String custmNo = "";
        //根据客户名查询客户编码
        List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber"
                ),
                // 组合两个过滤条件（规格型号 + 物料分组）
                String.format("FName = '%s' ",
                        cusName), null, 0, 0);
        if (!VtuzxUtil.isEmpty(prdcumQuery)) {
            custmNo = VtuzxUtil.getString(prdcumQuery.get(0), "FNumber");
        } else {
            throw new RuntimeException(String.format("金蝶客户不存在%s", custmNo));
        }

        return custmNo;
    }

    /**
     * 销售出库单传金蝶
     *
     * @param saleOutStock
     * @param saleOutStockDetailList
     * @throws Exception
     */
    public void syncSaleOutOrder(SaleOutStock saleOutStock, List<SaleOutStockDetail> saleOutStockDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }

        Map<String, Object> saleoutParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleoutModel = new LinkedHashMap<>();//单据头
        Map<String, Double> materialTotalMap = new HashMap<>(); // 物料总数量汇总
        Map<String, String> tyjhToMaterialMap = new HashMap<>(); // 客户件号到物料号的映射

        Map<String, String> wlflToMaterialMap = new HashMap<>(); // 客户件号到物料号的映射
        // 新增价格存储Map
        Map<String, String> taxPriceMap = new HashMap<>();
        Map<String, String> tyjhToUnitMap = new HashMap<>(); // 客户件号到单位的映射
        String cumNo = saleOutStock.getCustNo();//客户
        String cufid = saleOutStock.getBillNo();//销售订单号
        String custmNo = "";
        String xsddNo = "";
        String xsddflNo = "";
        //单据头
        saleoutModel.put("FID", 0);
        saleoutModel.put("FBillTypeID", new Document("FNUMBER", "XSCKD01_SYS"));//单据类型
        saleoutModel.put("FSaleOrgId", new Document("FNumber", "100"));//组织
        saleoutModel.put("FCustomerID", new Document("FNUMBER", "CUST0011"));//结算客户
        saleoutModel.put("FReceiverID", new Document("FNUMBER", "CUST0011"));//收货方
        saleoutModel.put("FSaleDeptID", new Document("FNUMBER", "CUST0011"));//销售部门
        saleoutModel.put("FStockOrgId", new Document("FNUMBER", "100"));//发货组织
        saleoutModel.put("FDate", DateUtils.dateToStr(saleOutStock.getIsDate(), "yyyy-MM-dd HH:mm:ss"));//日期
        saleoutModel.put("FSettleID", new Document("FNUMBER", "CUST0011"));//结算方
        saleoutModel.put("FPayerID", new Document("FNUMBER", "CUST0011"));//付款方
        saleoutModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//整单服务或费用
        saleoutModel.put("FIsTotalServiceOrCost", false);//整单服务或费用
        saleoutModel.put("F_PSUH_Text_83g", saleOutStock.getBillNo());//客户订单号-订单编号
        //根据客户名查询客户编码
        List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client, "BD_Customer", new VtuzxArrayList<>(
                        "FNumber"
                ),

                String.format("FName = '%s' ",
                        cumNo), null, 0, 0);
        if (!VtuzxUtil.isEmpty(prdcumQuery)) {
            custmNo = VtuzxUtil.getString(prdcumQuery.get(0), "FNumber");
        } else {
            throw new RuntimeException(String.format("金蝶客户不存在%s", cumNo));
        }
        saleoutModel.put("F_PSUH_Base_qtr", new Document("FNUMBER", custmNo));//终端客户
        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息
        saleFIn.put("FSettleCurrID", new Document("FNumber", "PRE001"));//结算币别
        saleoutModel.put("SubHeadEntity", saleFIn);

        // ================== 处理当前订单明细 ==================
        // 筛选当前订单的明细项
        List<SaleOutStockDetail> orderDetails = saleOutStockDetailList.stream()
                .filter(d -> d.getBillNo().trim().equals(saleOutStock.getBillNo().trim()))
                .collect(Collectors.toList());

        // 日志：输出当前订单和明细数量
        System.out.printf("Processing Order: %s, Details Count: %d%n", saleOutStock.getBillNo(), orderDetails.size());
        // [2.1 第一次遍历detailList: 查询物料信息并汇总数量]
        // 1. 物料信息查询与数量汇总
        for (SaleOutStockDetail detail : orderDetails) {
            String TYjh = detail.getTYNumber();

            if (!tyjhToMaterialMap.containsKey(TYjh)) {
                List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(
                        client, "BD_MATERIAL",
                        new VtuzxArrayList<>("FBaseUnitId.fnumber", "FNumber"),
                        String.format("FNumber = '%s' ", TYjh),
                        null, 0, 0
                );

                if (VtuzxUtil.isEmpty(prdInQuery)) {
                    throw new RuntimeException(String.format("物料不存在%s", TYjh));
                }

                tyjhToMaterialMap.put(TYjh, VtuzxUtil.getString(prdInQuery.get(0), "FNumber"));
                tyjhToUnitMap.put(TYjh, VtuzxUtil.getString(prdInQuery.get(0), "FBaseUnitId.fnumber"));
            }

            // 累加当前订单的物料数量
            String materialNo = tyjhToMaterialMap.get(TYjh);
            materialTotalMap.merge(materialNo, detail.getCount(), Double::sum);
        }

        // [2.2 库存检查]
        // 2. 库存检查（仅当前订单）
        for (Map.Entry<String, Double> entry : materialTotalMap.entrySet()) {
            String materialNo = entry.getKey();
            Double total = entry.getValue();

            List<VtuzxMap> prdKCQuery = vtuzxKingdeeService.query(
                    client, "STK_Inventory",
                    new VtuzxArrayList<>("FBaseQty"),
                    String.format("FMaterialId.FNumber = '%s'", materialNo),
                    null, 0, 0
            );

            if (VtuzxUtil.isEmpty(prdKCQuery)) {
                throw new RuntimeException(String.format("库存不存在%s", materialNo));
            }

            Double kcQty = Double.parseDouble(VtuzxUtil.getString(prdKCQuery.get(0), "FBaseQty"));
            if (kcQty < total) {
                throw new RuntimeException(String.format(
                        "订单%s库存不足: 物料%s 库存%.2f 需%.2f",
                        saleOutStock.getBillNo(), materialNo, kcQty, total
                ));
            }
        }
        //根据客户订单号查询销售订单ID
        List<VtuzxMap> prdfidQuery = vtuzxKingdeeService.query(client, "SAL_SaleOrder", new VtuzxArrayList<>(
                        "FID"
                ),
                String.format("F_PSUH_Text_qtr = '%s' ",
                        cufid), null, 0, 0);
        if (!VtuzxUtil.isEmpty(prdfidQuery)) {
            xsddNo = VtuzxUtil.getString(prdfidQuery.get(0), "FID");
        } else {
            throw new RuntimeException(String.format("销售订单中不存在该客户订单号%s", cufid));
        }


        //订单明细
        List<Map<String, Object>> FEntity = new ArrayList<>();//明细信息
        //添加明细信息
        for (SaleOutStockDetail detail : orderDetails) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            String TYjh = detail.getTYNumber().trim();
            // 查询销售订单分录信息（FENTRYID和FTaxPrice）
            if (!wlflToMaterialMap.containsKey(TYjh)) {
                List<VtuzxMap> prdwlflidQuery = vtuzxKingdeeService.query(
                        client,
                        "SAL_SaleOrder",
                        new VtuzxArrayList<>("FSaleOrderEntry_FENTRYID", "FTaxPrice"),
                        String.format(
                                "F_PSUH_Text_qtr = '%s' AND FMaterialId.FNumber = '%s'",
                                cufid,
                                tyjhToMaterialMap.get(TYjh)
                        ),
                        null, 0, 0
                );

                if (!VtuzxUtil.isEmpty(prdwlflidQuery)) {
                    String fEntryId = VtuzxUtil.getString(prdwlflidQuery.get(0), "FSaleOrderEntry_FENTRYID");
                    String taxPrice = VtuzxUtil.getString(prdwlflidQuery.get(0), "FTaxPrice");
                    wlflToMaterialMap.put(TYjh, fEntryId);
                    taxPriceMap.put(TYjh, taxPrice); // 存储含税价
                } else {
                    throw new RuntimeException("销售订单中未找到物料 " + TYjh + " 的分录信息");
                }
            }
            entryMap.put("FRowType", "Standard");
            entryMap.put("FRowType", "Standard");//物料编码
            entryMap.put("FMATERIALID", new Document("FNumber", tyjhToMaterialMap.get(TYjh)));
            entryMap.put("FUnitID", new Document("FNumber", tyjhToUnitMap.get(TYjh)));
            entryMap.put("FRealQty", detail.getCount());//实发数量
            entryMap.put("FRowType", "Standard");//托数
            entryMap.put("FSalUnitID", new Document("FNumber", tyjhToUnitMap.get(TYjh)));
            entryMap.put("FSALUNITQTY", detail.getCount());//销售数量
            entryMap.put("FSALBASEQTY", detail.getCount());//销售基本数量
            entryMap.put("FPRICEBASEQTY", detail.getCount());//机加基本数量
            entryMap.put("FOUTCONTROL", false);//托数
            entryMap.put("F_PSUH_Text_qtr", detail.getBoxNo());//箱号
            entryMap.put("F_PSUH_Text_83g1", detail.getPalletsNumber());//托数
            // 填充entryMap的FTaxPrice字段
            entryMap.put("FTaxPrice", taxPriceMap.get(TYjh));

            //添加linked信息(收料通知单关联)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();

            linkMap.put("FEntity_Link_FRuleId", "SaleOrder-OutStock");//下推规则
            linkMap.put("FEntity_Link_FSTableName", "T_SAL_ORDERENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBillId", xsddNo);//源单内码，同步收料通知单时将fid和fentryid同步到中台
            linkMap.put("FEntity_Link_FSId", wlflToMaterialMap.get(TYjh));// 源单分录内码
            linkList.add(linkMap);
            entryMap.put("FEntity_Link", linkList);
            FEntity.add(entryMap);

        }
        saleoutModel.put("FEntity", FEntity);
        saleoutParam.put("NeedUpDateFields", new ArrayList<>());
        saleoutParam.put("NeedReturnFields", new ArrayList<>());
        saleoutParam.put("IsDeleteEntry", true);
        saleoutParam.put("SubSystemId", "");
        saleoutParam.put("IsVerifyBaseDataField", false);
        saleoutParam.put("IsEntryBatchFill", true);
        saleoutParam.put("ValidateFlag", true);
        saleoutParam.put("NumberSearch", true);
        saleoutParam.put("IsAutoAdjustField", true);
        saleoutParam.put("InterationFlags", "");
        saleoutParam.put("IgnoreInterationFlag", "");
        saleoutParam.put("IsControlPrecision", false);
        saleoutParam.put("ValidateRepeatJson", false);
        saleoutParam.put("Model", saleoutModel);
        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "SAL_OUTSTOCK", saleoutParam);
            // 调试日志：打印 saleoutParam
            System.out.println("saleoutParam: " + new Gson().toJson(saleoutParam));
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
//            vtuzxKingdeeService.submit(client, "SAL_OUTSTOCK", "0", number);
//            vtuzxKingdeeService.audit(client, "SAL_OUTSTOCK", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace(); // 打印完整堆栈
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 异常处理单
     *
     * @param list
     * @throws Exception
     */
    public void syncAbnormal(Abnormal list) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        Map<String, Object> abParam = new LinkedHashMap<>();//传单param
        Map<String, Object> abModel = new LinkedHashMap<>();//单据头

        //单据头
        abModel.put("FID", 0);
        abModel.put("FBillNo", list.getBillNo());
        abModel.put("F_PUSH_CreateDate_fg2", list.getDate());
        abModel.put("F_PSUH_BILLTYPEID_K79", new Document("FNUMBER", "YCCLD"));

        //订单明细
        List<Map<String, Object>> PSUH_Cust_Entry100004 = new ArrayList<>();//明细信息
        Map<String, Object> entryMap = new LinkedHashMap<>();
        entryMap.put("F_PSUH_SourceBillNo_re5", list.getReceiveBillNo());
        entryMap.put("F_PSUH_TExt_yrr00", list.getPurBillNo());
        entryMap.put("F_PSUH_Decimal_apv", list.getSourceQty());
        entryMap.put("F_PSUH_Decimal_tzk", list.getAbnormalQty());
        entryMap.put("F_PSUH_Text_yrr", list.getPurBillNo());//采购订单编号
        entryMap.put("F_VKFP_Qty_ilb",list.getBcWeight());//本次数量
        entryMap.put("F_VKFP_Qty_25i",list.getBcWeight() - list.getAbnormalQty());//已补源单数量
        entryMap.put("F_psuh_Base_ca9", new Document("Fnumber", list.getMaterialNumber()));
        PSUH_Cust_Entry100004.add(entryMap);

        abModel.put("F_PSUH_Entity_qtr", PSUH_Cust_Entry100004);
        abParam.put("NeedUpDateFields", new ArrayList<>());
        abParam.put("NeedReturnFields", new ArrayList<>());
        abParam.put("IsDeleteEntry", true);
        abParam.put("SubSystemId", "");
        abParam.put("IsVerifyBaseDataField", false);
        abParam.put("IsEntryBatchFill", true);
        abParam.put("ValidateFlag", true);
        abParam.put("NumberSearch", true);
        abParam.put("InterationFlags", "");
        abParam.put("Model", abModel);
        Gson gson = new Gson();
        String json = gson.toJson(abParam);
        System.out.println(json);


        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PSUH_YCCLD", abParam);
//            VtuzxMap kingdeeCustomerMap = customerList.get(0);
//            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
//            vtuzxKingdeeService.submit(client, "PSUH_YCCLD", "0", number);
//            vtuzxKingdeeService.audit(client, "PSUH_YCCLD", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
        }
    }

    /**
     * 反审收料通知单
     *
     * @param user_id
     * @param userName
     * @param purIn
     * @param purInDetailList
     * @throws Exception
     */
    @Override
    public void unAuditPurReceive(Long user_id, String userName, PurIn purIn, List<PurInDetail> purInDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        try {
            //反审收料通知单
            vtuzxKingdeeService.unAudit(client, "PUR_ReceiveBill", "0", purIn.getReceiveBillNo());
        } catch (Exception e) {
        }

    }

    /**
     * 根据客户订单号查询金蝶销售订单
     *
     * @param cusBillNo 客户订单号
     * @return
     */
    private Map<String, Object> getKingdeeqingSaleOrder(String cusBillNo, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        Map<String, Object> data = new HashMap<>();
        List<Integer> entryList = new ArrayList<>();
        Integer fid = 0;
        String billNo = "";//金蝶销售订单号
        //根据客户订单号查询金蝶销售订单
        List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client, "SAL_SaleOrder", new VtuzxArrayList<>(
                        "FBillNo",
                        "FID",
                        "FSaleOrderEntry_FEntryID"
                ),

                String.format("F_PSUH_Text_qtr = '%s' ",
                        cusBillNo), null, 0, 0);

        if (!VtuzxUtil.isEmpty(prdcumQuery)) {
            fid = VtuzxUtil.getInt(prdcumQuery.get(0), "FID");
            billNo = VtuzxUtil.getString(prdcumQuery.get(0), "FBillNo");
            for (VtuzxMap vtuzxMap : prdcumQuery) {
                Integer FEntryID = VtuzxUtil.getInt(vtuzxMap, "FSaleOrderEntry_FEntryID");
                if (!entryList.contains(FEntryID)) {
                    entryList.add(FEntryID);
                }
            }
        } else {
            throw new RuntimeException(String.format("金蝶没有客户订单号为%s的销售订单", cusBillNo));
        }
        data.put("fid", fid);
        data.put("billNo", billNo);
        data.put("entryList", entryList);

        return data;
    }

    /**
     * 销售订单变更单
     *
     * @param saleOrder
     * @param saleOrderDetailList
     * @throws Exception
     */
    @Override
    public void syncSaleUpdateOrder(SaleOrder saleOrder, List<SaleOrderDetail> saleOrderDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        String cusBillNo = saleOrder.getCusBillNo();//客户订单号
        Map<String, Object> kingdeeSaleOrder = getKingdeeSaleOrder(cusBillNo);
        VtuzxMap orderParam = new VtuzxMap();
        VtuzxMap orderArgs = new VtuzxMap();
        orderArgs.append("SaleOrderBillNo", VtuzxUtil.getString(kingdeeSaleOrder, "billNo"));
        orderArgs.append("SaleOrderBillId", VtuzxUtil.getString(kingdeeSaleOrder, "fid"));
        orderArgs.append("SOEntryIds", VtuzxUtil.getObject(kingdeeSaleOrder, "entryList"));
        orderParam.append("saveXSaleOrderArgs", orderArgs);
        List<Map<String, Object>> customerList = new ArrayList<>();
        try {
            //先调用销售订单变更单
            customerList = vtuzxKingdeeService.orderUp(client, "SAL_XORDER", orderArgs);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        Map<String, Object> matMap = new HashMap<>();//key:物料id，val:单价
        Map<String, Object> detailMap = new HashMap<>();//key:物料内码，val:订单详情
        for (SaleOrderDetail detail : saleOrderDetailList) {
            String tyNo = detail.getTyPartNo();//客户件号
            Double taxPrice = detail.getTaxPrice();
            String FMATERIALID = "";
            //根据物料件号(编码)查询内码
            List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FMATERIALID"
                    ),
                    String.format("FNumber = '%s'", tyNo), null, 0, 0);
            if (!VtuzxUtil.isEmpty(prdInQuery)) {
                FMATERIALID = VtuzxUtil.getString(prdInQuery.get(0), "FMATERIALID");
            } else {
                throw new RuntimeException(String.format("金蝶不存在物料%s", tyNo));
            }
            matMap.put(FMATERIALID, taxPrice);
            detailMap.put(FMATERIALID, detail);

        }
        List<Map<String, Object>> entryList = VtuzxUtil.getObject(customerList.get(0), "SaleOrderEntry");//变更单返回的明细
        String fid = VtuzxUtil.getString(customerList.get(0), "FID");//单据头id
        Map<String, Object> kingEntryMap = new HashMap<>();//key:物料内码 val;金蝶单据体内码
        for (Map<String, Object> entryMap : entryList) {
            String materialId = VtuzxUtil.getString(entryMap, "FMaterialId");
            String entryId = VtuzxUtil.getString(entryMap, "FEntryID");
            kingEntryMap.put(materialId, entryId);
        }

        List<Map<String, Object>> orderEntryList = new ArrayList<>();//需要保存的单据体数据
        //循环订单明细添加变更单信息(FChangeType变更类型D删除，A修改，B新增)
        for (Map.Entry entry : detailMap.entrySet()) {
            String materialId = (String) entry.getKey();//物料内码
            SaleOrderDetail orderDetail = (SaleOrderDetail) entry.getValue();//详情数据
            String type = orderDetail.getType();
            //新增的话不需要entryid
            if ("新增".equals(type)) {
                Map<String, Object> kingdeeEntry = new HashMap<>();
                String tyNo = orderDetail.getTyPartNo();//ty件号
                kingdeeEntry.put("FRowType", "Standard");
                String unitNo = "";
                String materialNo = "";
                //根据ty件号(对应金蝶物料编码)查询单位编码
                List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FBaseUnitId.fnumber",
                                "FNumber"
                        ),
                        String.format("FNumber = '%s'", tyNo), null, 0, 0);
                if (!VtuzxUtil.isEmpty(prdInQuery)) {
                    unitNo = VtuzxUtil.getString(prdInQuery.get(0), "FBaseUnitId.fnumber");
                    materialNo = VtuzxUtil.getString(prdInQuery.get(0), "FNumber");
                } else {
                    throw new RuntimeException(String.format("金蝶不存在物料%s", tyNo));
                }
                kingdeeEntry.put("FMATERIALID", new Document("FNumber", materialNo));//物料编码
                kingdeeEntry.put("FUnitID", new Document("FNumber", unitNo));//单位
                kingdeeEntry.put("Fqty", orderDetail.getQty());//销售数量
                kingdeeEntry.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
                kingdeeEntry.put("FTaxPrice", orderDetail.getTaxPrice());//含税单价
                kingdeeEntry.put("FEntryTaxRate", orderDetail.getTaxRate());//税率
                kingdeeEntry.put("FDeliveryDate", DateUtils.dateToStr(orderDetail.getDeliveDate(), "yyyy-MM-dd HH:mm:ss"));//交货期
                kingdeeEntry.put("F_PSUH_Date_ca9", DateUtils.dateToStr(orderDetail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
                kingdeeEntry.put("F_PSUH_Integer_apv", orderDetail.getShipWeek());//船期周数
                kingdeeEntry.put("F_PSUH_Integer_tzk", orderDetail.getDeliveWeek());//计划出货周数
                kingdeeEntry.put("FChangeType", "A");
                orderEntryList.add(kingdeeEntry);
            } else if ("删除".equals(type)) {
                String entryId = VtuzxUtil.getString(kingEntryMap, materialId);//详情内码
                Map<String, Object> kingdeeEntry = new HashMap<>();
                kingdeeEntry.put("FEntryId", entryId);
                kingdeeEntry.put("FChangeType", "D");
                orderEntryList.add(kingdeeEntry);
            } else {//修改
                String entryId = VtuzxUtil.getString(kingEntryMap, materialId);//详情内码
                Map<String, Object> kingdeeEntry = new HashMap<>();
                String tyNo = orderDetail.getTyPartNo();//ty件号
                kingdeeEntry.put("FRowType", "Standard");
                kingdeeEntry.put("FEntryId", entryId);
                String unitNo = "";
                String materialNo = "";
                //根据ty件号(对应金蝶物料编码)查询单位编码
                List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FBaseUnitId.fnumber",
                                "FNumber"
                        ),
                        String.format("FNumber = '%s'", tyNo), null, 0, 0);
                if (!VtuzxUtil.isEmpty(prdInQuery)) {
                    unitNo = VtuzxUtil.getString(prdInQuery.get(0), "FBaseUnitId.fnumber");
                    materialNo = VtuzxUtil.getString(prdInQuery.get(0), "FNumber");
                } else {
                    throw new RuntimeException(String.format("金蝶不存在物料%s", tyNo));
                }
                kingdeeEntry.put("FMATERIALID", new Document("FNumber", materialNo));//物料编码
                kingdeeEntry.put("FUnitID", new Document("FNumber", unitNo));//单位
                kingdeeEntry.put("Fqty", orderDetail.getQty());//销售数量
                kingdeeEntry.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
                kingdeeEntry.put("FTaxPrice", orderDetail.getTaxPrice());//含税单价
                kingdeeEntry.put("FEntryTaxRate", orderDetail.getTaxRate());//税率
                kingdeeEntry.put("FDeliveryDate", DateUtils.dateToStr(orderDetail.getDeliveDate(), "yyyy-MM-dd HH:mm:ss"));//交货期
                kingdeeEntry.put("F_PSUH_Date_ca9", DateUtils.dateToStr(orderDetail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
                kingdeeEntry.put("F_PSUH_Integer_apv", orderDetail.getShipWeek());//船期周数
                kingdeeEntry.put("F_PSUH_Integer_tzk", orderDetail.getDeliveWeek());//计划出货周数
                kingdeeEntry.put("FChangeType", "B");
                orderEntryList.add(kingdeeEntry);
            }
        }


        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头

        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息
        //查询币别的编码
        String currency = saleOrderDetailList.get(0).getCurrency();//币别
        String currentyNo = "";
        //根据ty件号(对应金蝶物料编码)查询单位编码
        List<VtuzxMap> currenQuery = vtuzxKingdeeService.query(client, "BD_Currency", new VtuzxArrayList<>(
                        "FNumber"
                ),
                String.format("FName = '%s'", currency), null, 0, 0);
        if (!VtuzxUtil.isEmpty(currenQuery)) {
            currentyNo = VtuzxUtil.getString(currenQuery.get(0), "FNumber");
        } else {
            throw new RuntimeException(String.format("金蝶不存在币别%s", currency));
        }

        saleFIn.put("FSettleCurrId", new Document("FNumber", currentyNo));//结算币别
        saleModel.put("FSaleOrderFinance", saleFIn);

        saleModel.put("FID", fid);
        saleModel.put("FSaleOrderEntry", orderEntryList);
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("Model", saleModel);
        try {
            List<VtuzxMap> sal_xorder = vtuzxKingdeeService.save(client, "SAL_XORDER", saleParam);
            VtuzxMap kingdeeCustomerMap = sal_xorder.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "SAL_XORDER", "0", number);
            vtuzxKingdeeService.audit(client, "SAL_XORDER", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public void syncPrdOrder(SfcOperp sfcOperp, List<SfcOperpDetail> sfcOperpDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头
        //查询单据类型
        String typeNo = getOrderType(sfcOperp.getType(), client);
        //单据头
        saleModel.put("FBillNo", sfcOperp.getBillNo());//单据编号
        saleModel.put("FDescription", sfcOperp.getRemark());//备注
        saleModel.put("FBillType", new Document("FNUMBER", typeNo));//单据类型
        saleModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        saleModel.put("FDate", DateUtils.dateToStr(sfcOperp.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));//单据日期
        saleModel.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
        saleModel.put("FPPBOMType", 1);//用料清单展开
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (SfcOperpDetail detail : sfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
//            entryMap.put("FUnitId",new Document("FNumber",detail.getUnitNo()));//单位
            //TODO 产品类型
            entryMap.put("Fqty", detail.getQty());//数量
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间
            if ("外协".equals(detail.getMaterialType())) {
                if (VtuzxUtil.isEmpty(detail.getBOMType())) {//如果外协的没有制指定bom版本
                    throw new RuntimeException("产品类型是外协的请指定bom版本");
                } else {
                    entryMap.put("FBomId", new Document("FNumber", detail.getBOMType()));//bom版本
                }

            }
            orderEntry.add(entryMap);

        }
        saleModel.put("FTreeEntity", orderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_MO", saleParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_MO", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_MO", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 根据客户订单号查询金蝶销售订单
     *
     * @param cusBillNo 客户订单号
     * @return
     */
    private Map<String, Object> getKingdeeSaleOrder(String cusBillNo) throws Exception {
        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
        Map<String, Object> data = new HashMap<>();
        List<Integer> entryList = new ArrayList<>();
        Integer fid = 0;
        String billNo = "";//金蝶销售订单号
        //根据客户订单号查询金蝶销售订单
        List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client, "SAL_SaleOrder", new VtuzxArrayList<>(
                        "FBillNo",
                        "FID",
                        "FSaleOrderEntry_FEntryID"
                ),
                // 组合两个过滤条件（规格型号 + 物料分组）
                String.format("F_PSUH_Text_qtr = '%s' ",
                        cusBillNo), null, 0, 0);

        if (!VtuzxUtil.isEmpty(prdcumQuery)) {
            fid = VtuzxUtil.getInt(prdcumQuery.get(0), "FID");
            billNo = VtuzxUtil.getString(prdcumQuery.get(0), "FBillNo");
            for (VtuzxMap vtuzxMap : prdcumQuery) {
                Integer FEntryID = VtuzxUtil.getInt(vtuzxMap, "FSaleOrderEntry_FEntryID");
                if (!entryList.contains(FEntryID)) {
                    entryList.add(FEntryID);
                }
            }
        } else {
            throw new RuntimeException(String.format("金蝶没有客户订单号为%s的销售订单", cusBillNo));
        }
        data.put("fid", fid);
        data.put("billNo", billNo);
        data.put("entryList", entryList);

        return data;
    }

    /**
     * 查询单据类型
     *
     * @param type
     * @return
     * @throws Exception
     */
    private String getOrderType(String type, VtuzxKingdeeCloudClient client) throws Exception {
        String typeNo = "";
        List<VtuzxMap> typeQuery = vtuzxKingdeeService.query(client, "BOS_BillType", new VtuzxArrayList<>(
                        "Fnumber"
                ),
                String.format("FName = '%s'", type), null, 0, 1);//根据物料仓库查询数量
        if (!VtuzxUtil.isEmpty(typeQuery)) {
            typeNo = VtuzxUtil.getString(typeQuery.get(0), "Fnumber");
        } else {
            throw new RuntimeException(String.format("金蝶不存生产类型:%s", type));
        }
        return typeNo;
    }

//    /**
//     * 来料检验单
//     * @param list
//     * @param inspectDetails
//     * @throws Exception
//     */
//    public void syncInspect(List<Inspect> list,List<InspectDetail> inspectDetails) throws Exception {
//        //        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
//        Map<String, Object> abParam = new LinkedHashMap<>();//传单param
//        Map<String, Object> abModel = new LinkedHashMap<>();//单据头
//
//    }


    /**
     * 传金蝶生产领料
     *
     * @param prdPick
     * @param detailList
     * @throws Exception
     */
    public void syncPrdPick(Long userId, PrdPick prdPick, List<PickDetail> detailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(userId);
        } catch (Exception e){
            throw new RuntimeException("金蝶账号密码错误请维护");
        }
        Map<String, Object> pickModel = new LinkedHashMap<>();//金蝶领料单model
        pickModel.put("FID",0);//实体主键
        pickModel.put("FBillType",new VtuzxMap("FNUMBER","SCLLD01_SYS"));//单据类型
        pickModel.put("FDate", DateUtils.dateToStr(prdPick.getFDATE(),"yyyy-MM-dd"));//单据日期
        pickModel.put("FStockOrgId",new VtuzxMap("FNUMBER","100"));//发料组织
        pickModel.put("FPrdOrgId",new VtuzxMap("FNUMBER","100"));//生产组织
        pickModel.put("FWorkShopId",new VtuzxMap("FNUMBER","JJ"));//车间默认机加车间
        pickModel.put("FSTOCKERID",new VtuzxMap("FNAME","王英爽"));//仓管员
        pickModel.put("FDescription",prdPick.getFBILLNO());//中台补料单号
        List<Map<String,Object>> FEntity  = new ArrayList<>();//明细信息
        String fbillnomo = prdPick.getFBILLNOMO();//生产订单号
        SfcProplan sfcProplan = sfcProplanDao.selectOne(new LambdaQueryWrapper<SfcProplan>()
                .eq(SfcProplan::getMoBillNo, fbillnomo));


        for (PickDetail detail : detailList){
            String materialNo = detail.getFMATERIALNUMBER();
            //查询用料清单编号
            PpBom ppBom = ppBomDao.selectOne(new LambdaQueryWrapper<PpBom>().eq(PpBom::getFMOBILLNO, fbillnomo)
                    .eq(PpBom::getFMATERIALNUMBER,materialNo));
            String ppbomNo = ppBom.getFBILLNO();//用料清单单据编号


            Map<String,Object> entity = new LinkedHashMap<>();//金蝶明细信息
            entity.put("FParentMaterialId",new VtuzxMap("FNumber",sfcProplan.getMaterialNo()));//物料编码
            entity.put("FMaterialId",new VtuzxMap("FNumber",detail.getFMATERIALNUMBER()));//物料编码
            //这个物料编码是订单上的物料编码
            entity.put("FUnitID",new VtuzxMap("FNumber",detail.getFUNITID()));//基本单位
            entity.put("FAppQty",detail.getFINFACTQTY());//申请数量
            entity.put("FActualQty",detail.getFINFACTQTY());//实发数量
            entity.put("FStockId",new VtuzxMap("FNumber","CK003"));//仓库默认毛坯库
            entity.put("FLot",new VtuzxMap("FNumber",detail.getFLOT()));//批号


            entity.put("FMoBillNo",fbillnomo);//生产订单编号
            entity.put("FPPBomBillNo",ppbomNo);//用料清单编号
            entity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型

            entity.put("FBaseActualQty",detail.getFINFACTQTY());//基本单位实发数量
            entity.put("FBaseStockActualQty",detail.getFINFACTQTY());//基本单位实发数量
            entity.put("FEntryWorkShopId",new VtuzxMap("FNumber","JJ"));//车间

            entity.put("FBaseUnitId",new VtuzxMap("FNumber",detail.getFUNITID()));//基本单位
            //查询库存辅助单位
            String FStockUnitId = "";
            List<VtuzxMap> unitQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FAuxUnitID.fnumber"
                    ),
                    String.format("FNUMBER = '%s'",detail.getFMATERIALNUMBER() ), null, 0, 1);
            if (!VtuzxUtil.isEmpty(unitQuery)) {
                FStockUnitId = VtuzxUtil.getString(unitQuery.get(0),"FAuxUnitID.fnumber");//辅助单位
            }
            entity.put("FStockUnitId",new VtuzxMap("FNumber",detail.getFUNITID()));//库存单位
            entity.put("FSecUnitId",new VtuzxMap("FNumber",FStockUnitId));//辅助单位


            entity.put("FOwnerId",new VtuzxMap("FNumber","100"));//货主
            entity.put("FParentOwnerTypeId","BD_OwnerOrg");//产品货主类型
            entity.put("FParentOwnerId",new VtuzxMap("FNumber","100"));//产品货主

            //查询用料清单获取
            String FId = "";//原单内码
            String FEntryId = "";//分录内码
            //查询原单内码和分录内码
            List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "PRD_PPBOM", new VtuzxArrayList<>(
                            "FId",
                            "FEntity_FEntryID"//分录内码
                    ),
                    String.format("FBillNo = '%s' and FMaterialId2.FNumber = '%s'", ppbomNo,detail.getFMATERIALNUMBER()), null, 0, 1);
            if (!VtuzxUtil.isEmpty(prdInQuery)) {
                FId = VtuzxUtil.getString(prdInQuery.get(0),"FId");
                FEntryId = VtuzxUtil.getString(prdInQuery.get(0),"FEntity_FEntryID");
            }
            //查询生产订单内码
            String moEntryId = "";
            List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MO", new VtuzxArrayList<>(
                            "FTreeEntity_FEntryID"

                    ),
                    String.format("FBillNo = '%s'", fbillnomo), null, 0, 1);

            if (!VtuzxUtil.isEmpty(moQuery)) {
                moEntryId = VtuzxUtil.getString(moQuery.get(0),"FTreeEntity_FEntryID");//生产订单分录内码
            }
            entity.put("FMoEntryId",moEntryId);//生产订单分录内码
            entity.put("FPPBomEntryId",FEntryId);//用料清单分录内码
            //添加link信息(用料清单关联)
            List<Map<String,Object>> linkList = new ArrayList<>();
            Map<String,Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRuleId","ea808801-aef0-84fd-11f0-830bdaa3b1e8");//下推规则
            //linkMap.put("FEntity_Link_FRuleId","3be192e7-0961-4236-90d2-c7c21263e307");//下推规则
            linkMap.put("FEntity_Link_FSTableName","T_PRD_PPBOMENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBillId",FId);//源单内码
            linkMap.put("FEntity_Link_FSId",FEntryId);// 源单分录内码
            linkList.add(linkMap);
            entity.put("FEntity_Link",linkList);
            FEntity.add(entity);
        }
        pickModel.put("FEntity",FEntity);
        Map<String,Object> param = new HashMap<>();//传单总参
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("InterationFlags", "");
        param.put("IsAutoAdjustField",true);
        param.put("Model", pickModel);
        try {
            List<VtuzxMap> pickList = vtuzxKingdeeService.save(client, "PRD_PickMtrl", param);
            VtuzxMap prdReturnMap = pickList.get(0);
            String number = VtuzxUtil.getString(prdReturnMap, "Number");
            //中台保存金蝶单据编号
            savePickKingNo(prdPick,number);
            vtuzxKingdeeService.submit(client, "PRD_PickMtrl", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_PickMtrl", "0", number, "STK_InvCheckResult");
        } catch (Exception e){

            throw new RuntimeException(e.getMessage());
        }


    }

    /**
     * 中台保存金蝶单据编号
     * @param prdPick
     * @param kingdeeNo
     */
    private void savePickKingNo(PrdPick prdPick,String kingdeeNo){
        prdPick.setFKDBILLNO(kingdeeNo);
        prdPickDao.updateById(prdPick);
    }
    /**
     * 上传生产订单变更单
     *
     * @param sfcOperp
     * @param sfcOperpDetailList
     * @param user_id
     * @throws Exception
     */
    @Override
    public void syncPrdOrderUpdate(SfcOperp sfcOperp, List<SfcOperpDetail> sfcOperpDetailList, Long user_id, Map<String, Object> countMap) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //查询出订单fid和entryid,还有订单的数量(防止没有在中台做变更没传过去)
        String fid = "";
        String entryId = "";
        double orderCount = 0.0;
        String FConveyDate = "";//变更单的日期为生产订单的下达日期
        List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MO", new VtuzxArrayList<>(
                        "FID",
                        "FQty",
                        "FTreeEntity_FEntryId",
                        "FConveyDate"//下达日期
                ),
                String.format("FBillNo = '%s'", sfcOperp.getBillNo()), null, 0, 0);
        if (!VtuzxUtil.isEmpty(moQuery)) {
            fid = VtuzxUtil.getString(moQuery.get(0), "FID");
            entryId = VtuzxUtil.getString(moQuery.get(0), "FTreeEntity_FEntryId");
            orderCount = VtuzxUtil.getDouble(moQuery.get(0), "FQty");
            FConveyDate = VtuzxUtil.getString(moQuery.get(0), "FConveyDate");
        } else {
            throw new RuntimeException(String.format("金蝶不存在订单编号为%s的订单", sfcOperp.getBillNo()));
        }

        //判断变更单是否上传过(保存状态的不让重复传，审核的可以传)
        List<VtuzxMap> moUpdateQuery = vtuzxKingdeeService.query(client, "PRD_MOChange", new VtuzxArrayList<>(
                        "FBillNo"
                ),
                String.format("FMoId = '%s' and FMoEntryId = '%s' and  FDocumentStatus != 'C' ", fid, entryId), null, 0, 0);
        if (!VtuzxUtil.isEmpty(moUpdateQuery)) {
            throw new RuntimeException(String.format("订单编号为%s的订单已经上传过变更单,单据编号为%s", sfcOperp.getBillNo(), VtuzxUtil.getString(moUpdateQuery.get(0), "FBillNo")));
        }

        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头

        //TODO 校验数量变更数量不能小于领料+ 补料 - 退料(根据用料清单中的已领数量判断，找发料方式，是直接领料的)
        Double pickedQty = 0.0;//已领数量
        List<VtuzxMap> ppbomQuery = vtuzxKingdeeService.query(client, "PRD_PPBOM", new VtuzxArrayList<>(
                        "FPickedQty",//已领数量
                        "FBillNo"
                ),
                String.format("FMOBILLNO = '%s' and FIssueType = '1'", sfcOperp.getBillNo()), null, 0, 0);
        if (!VtuzxUtil.isEmpty(ppbomQuery)) {
            pickedQty = VtuzxUtil.getDouble(ppbomQuery.get(0), "FPickedQty");
        }
        Double count = VtuzxUtil.getDouble(countMap, sfcOperp.getBillNo() + "_" + sfcOperpDetailList.get(0).getMaterialNo());
        if (count == 0) {
            throw new RuntimeException(String.format("订单编号:%s中的物料信息与原订单物料信息不一致,请确认", sfcOperp.getBillNo()));
        }
        if (count < pickedQty) {
            throw new RuntimeException("变更数量不能小于已领数量");
        }
        //单据头
        saleModel.put("FBillType", new Document("FNUMBER", "SCDDBGD01_SYS"));//单据类型
        saleModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        saleModel.put("FDate", FConveyDate);//单据日期为生产订单的下达日期
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (SfcOperpDetail detail : sfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FChangeType", "2");//变更类型
            entryMap.put("FProductType", "1");//产品类型
            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FMoNo", sfcOperp.getBillNo());//生产订单编号
            entryMap.put("FMoEntrySeq", 1);//生产订单行号
            entryMap.put("FUnitId", new Document("FNumber", detail.getUnitNo()));//单位
            entryMap.put("FQty", orderCount);//数量
            entryMap.put("FStatus", "2");//业务状态
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间
            entryMap.put("FMoId", fid);//生产订单内码
            entryMap.put("FMoEntryId", entryId);//生产订单分录内码

            entryMap.put("FStockInOrgId", new Document("FNumber", "100"));//入库组织
            entryMap.put("FReqType", "1");//需求类型1
            entryMap.put("FSrcBillType", "PRD_MO");//源单类型
            entryMap.put("FSrcBillNo", detail.getBillNo());//源单编号
            entryMap.put("FSrcBillId", fid);//源单内码
            entryMap.put("FSrcBillEntryId", entryId);//源单分录内码
            entryMap.put("FSrcBillEntrySeq", 1);//源单行好
            //添加linked信息(关联生产订单)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRULEID", "PRD_MO2MOCHANGE");//下推规则
            linkMap.put("FEntity_Link_FSTABLENAME", "T_PRD_MOENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBILLID", fid);//源单内码
            linkMap.put("FEntity_Link_FSID", entryId);// 源单分录内码
            linkMap.put("FEntity_Link_FBaseQtyOld", orderCount);// 原始携带量
            linkMap.put("FEntity_Link_FBaseQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//修改携带量
            linkList.add(linkMap);
            entryMap.put("FEntity_Link", linkList);

            orderEntry.add(entryMap);

        }
        //变更后
        for (SfcOperpDetail detail : sfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FChangeType", "3");//变更类型
            entryMap.put("FProductType", "1");//产品类型
            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FMoNo", sfcOperp.getBillNo());//生产订单编号
            entryMap.put("FMoEntrySeq", 1);//生产订单行号
            entryMap.put("FUnitId", new Document("FNumber", detail.getUnitNo()));//单位
            entryMap.put("FQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//数量
            entryMap.put("FStatus", "2");//业务状态
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间
            entryMap.put("FMoId", fid);//生产订单内码
            entryMap.put("FMoEntryId", entryId);//生产订单分录内码

            entryMap.put("FStockInOrgId", new Document("FNumber", "100"));//入库组织
            entryMap.put("FReqType", "1");//需求类型1
            entryMap.put("FSrcBillType", "PRD_MO");//源单类型
            entryMap.put("FSrcBillNo", detail.getBillNo());//源单编号
            entryMap.put("FSrcBillId", fid);//源单内码
            entryMap.put("FSrcBillEntryId", entryId);//源单分录内码
            entryMap.put("FSrcBillEntrySeq", 2);//源单分录行
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRULEID", "PRD_MO2MOCHANGE");//下推规则
            linkMap.put("FEntity_Link_FSTABLENAME", "T_PRD_MOENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBILLID", fid);//源单内码
            linkMap.put("FEntity_Link_FSID", entryId);// 源单分录内码
            linkMap.put("FEntity_Link_FBaseQtyOld", orderCount);// 原始携带量
            linkMap.put("FEntity_Link_FBaseQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//修改携带量
            linkList.add(linkMap);
            entryMap.put("FEntity_Link", linkList);
            orderEntry.add(entryMap);

        }
        saleModel.put("FEntity", orderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_MOChange", saleParam);
//            VtuzxMap kingdeeCustomerMap = customerList.get(0);
//            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
//            vtuzxKingdeeService.submit(client, "PRD_MOChange", "0", number);
//            vtuzxKingdeeService.audit(client, "PRD_MOChange", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 模具大修的需要生成生产订单
     *
     * @param userName
     * @param moldInspect
     * @throws Exception
     */
    @Override
    public void syncPrdOrderMold(Long user_id, String userName, MoldInspect moldInspect) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        int moldId = moldInspect.getMoldId();
        MoldMaterial moldMaterial = moldMaterialDao.selectById(moldId);

        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头
        //查询单据类型
        //单据头
//        saleModel.put("FBillNo",sfcOperp.getBillNo());//单据编号
//        saleModel.put("FDescription",sfcOperp.getRemark());//备注
        saleModel.put("FBillType", new Document("FNUMBER", "SCDD02_SYS"));//单据类型
        saleModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        saleModel.put("FDate", DateUtils.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));//单据日期
        saleModel.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
        saleModel.put("FPPBOMType", 1);//用料清单展开
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        Map<String, Object> entryMap = new LinkedHashMap<>();
        entryMap.put("FMATERIALID", new Document("FNumber", moldInspect.getMaterialNo()));//物料编码
        entryMap.put("FUnitId", new Document("FNumber", moldMaterial.getUnitNumber()));//单位

        entryMap.put("Fqty", 1);//数量

        orderEntry.add(entryMap);


        saleModel.put("FTreeEntity", orderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_MO", saleParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_MO", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_MO", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 传金蝶调拨单
     * @param userId
     * @param pick
     * @param detailList
     * @throws Exception
     */
    @Override
    public void syncAllocation(Long userId, PrdPick pick, List<PickDetail> detailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(userId);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }

        Map<String, Object> param = new LinkedHashMap<>();

        List<Map<String, Object>> stockTransferEntryList = new ArrayList<>();//存放单据体数据
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID",new VtuzxMap("FNUMBER","ZJDB01_SYS"));//单据类型
        model.put("FBizType","NORMAL");//业务类型
        model.put("FTransferDirect","GENERAL");//调拨方向
        model.put("FTransferBizType","InnerOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber","100"));//结算组织
        model.put("FSaleOrgId",new VtuzxMap("FNumber","100"));//销售组织
        model.put("FStockOutOrgId",new VtuzxMap("FNumber","100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead",new VtuzxMap("FNumber","100"));//调出货主
        model.put("FStockOrgId",new VtuzxMap("FNumber","100"));//调入库存组织
        model.put("FIsIncludedTax",true);//是否含税
        model.put("FIsPriceExcludeTax",true);//价外税
        model.put("FExchangeTypeId",new VtuzxMap("FNUMBER","HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
        model.put("FDate", VtuzxUtil.formatYmdHmsF(pick.getFDATE()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign",false);//冲减普通寄售调拔单结算数量
        model.put("FNote", pick.getFBILLNO());

        //单据体数据
        for (PickDetail pickDetail : detailList){
            String materialNo  = pickDetail.getFMATERIALNUMBER();

            //判断是否启用批号,查询辅助单位
            String floatCond = String.format("FNumber = '%s'", materialNo);
            List<VtuzxMap> bd_Material = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage",
                    "FBaseUnitId",
                    "FAuxUnitID.fnumber"//辅助单位
            ), floatCond);
            boolean FIsBatchManage = true;//是否启用批号

            String FAuxUnitID = "";
            if (bd_Material != null && bd_Material.size() > 0) {
                FIsBatchManage = bd_Material.get(0).getBoolean("FIsBatchManage");
                FAuxUnitID = bd_Material.get(0).getString("FAuxUnitID.fnumber");
            }


            Map<String, Object> stockTransferEntry = new LinkedHashMap<>();
            stockTransferEntry.put("FMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FUnitID", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FQty", pickDetail.getFINFACTQTY());//数量
            if(FIsBatchManage){
                stockTransferEntry.put("FLot", new VtuzxMap("FNumber", pickDetail.getFLOT()));
            }
            stockTransferEntry.put("FLot", new VtuzxMap("FNumber", pickDetail.getFLOT()));
            stockTransferEntry.put("FSrcStockId", new VtuzxMap("FNumber", "CK002"));//调出仓库是砂芯库
            stockTransferEntry.put("FDestStockId", new VtuzxMap("FNumber", "CK018"));//调入仓库是铸造材料库
            stockTransferEntry.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            stockTransferEntry.put("FOwnerTypeOutId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FOwnerTypeId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FSecUnitId", new VtuzxMap("FNumber", FAuxUnitID));//库存辅助单位
            stockTransferEntry.put("FBaseUnitId", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FBaseQty", pickDetail.getFINFACTQTY());
            stockTransferEntry.put("FISFREE", false);
            stockTransferEntry.put("FKeeperTypeId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FKeeperTypeOutId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FDestLot", new VtuzxMap("FNumber", pickDetail.getFLOT()));
            stockTransferEntry.put("FDestMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FSaleUnitId", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
//            stockTransferEntry.put("FPriceUnitID", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FTransReserveLink", false);
            stockTransferEntry.put("FCheckDelivery", false);
            stockTransferEntryList.add(stockTransferEntry);


        }
        model.put("FBillEntry",stockTransferEntryList);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField",false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag","");
        param.put("IsControlPrecision",false);
        param.put("ValidateRepeatJson",false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = vtuzxKingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            pick.setFKDBILLNO(number);
            vtuzxKingdeeService.submit(client, "STK_TransferDirect", "0", number);
            vtuzxKingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void syncPrdReport(Long user_id, SfcOptrpt sfcOptrpt, List<SfcOptrptDetail> sfcOptrptDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据工序单号和工序查询工序计划的entryid,用于下推
        String erpBillNo = sfcOptrpt.getErpBillNo();//工序计划单号
        Long operpNo = sfcOptrpt.getOperpNo();//工序号

        String floatCond = String.format("fbillno = '%s' and FOperNumber  = '%s'", erpBillNo,operpNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationPlanning", new VtuzxArrayList<>(
                "FSubEntity_FDetailID"//分录id
        ), floatCond);
        String entryID = "";
        if (!VtuzxUtil.isEmpty(planList)){
            entryID = VtuzxUtil.getString(planList.get(0),"FSubEntity_FDetailID");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", erpBillNo);//单据编码集合
        model.put("EntryIds", "");//分录内码
//        model.put("RuleId", "82ddfcf2-199a-4e82-8fc7-2efc4fad532e");//转换规则内码
        model.put("RuleId", "SFC_OPRTPLAN2OPTRRPT");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推工序汇报单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationPlanning", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的汇报单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的汇报单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDescription", sfcOptrpt.getBillNo());//备注暂时存中台汇报单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        for (SfcOptrptDetail sfcOptrptDetail : sfcOptrptDetailList ){
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FOperNumber",operpNo);//工序号
            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FQuaQty",sfcOptrptDetail.getQuaQty());//合格数量
            entryMap.put("FProcessFailQty",sfcOptrptDetail.getProcessFailQty());//工废数量
            entryMap.put("FMaterialFailQty",sfcOptrptDetail.getMaterialFailQty());//料废数量
            entryMap.put("FFinishQty",sfcOptrptDetail.getEndQty());//完工数量
            FEntity.add(entryMap);
        }
        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "SFC_OperationReport", updateParam);
            vtuzxKingdeeService.submit(client, "SFC_OperationReport", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "SFC_OperationReport", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }


    }

    /**
     * 包装间传汇报单
     * @param user_id
     * @param sfcOptrpt
     * @param sfcOptrptDetailList
     * @throws Exception
     */
    @Override
    public void syncPrdReportBao(Long user_id, SfcOptrptPackage sfcOptrpt, List<SfcOptrptDetail> sfcOptrptDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据工序单号和工序查询工序计划的entryid,用于下推
        String erpBillNo = sfcOptrpt.getPlanNo();//工序计划单号

        //工序计划下推工序汇报
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", erpBillNo);//单据编码集合
        model.put("EntryIds", "");//分录内码
//        model.put("RuleId", "82ddfcf2-199a-4e82-8fc7-2efc4fad532e");//转换规则内码
        model.put("RuleId", "SFC_OPRTPLAN2OPTRRPT");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推工序汇报单
        List<VtuzxMap> optrptList = new ArrayList<>();
        try {
            optrptList = vtuzxKingdeeService.push(client, "SFC_OperationPlanning", model);
        } catch (Exception e){

            _logger.info(e.getMessage());
        }
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的汇报单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的汇报单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDate", DateUtils.dateToStr(sfcOptrpt.getFDate(),"yyyy-MM-dd HH:mm:ss"));

        updateModle.put("FDescription", sfcOptrpt.getBillNo());//备注暂时存中台汇报单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
//        for (SfcOptrptDetail sfcOptrptDetail : sfcOptrptDetailList ){
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FOperNumber",10);//工序号
            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FQuaQty",sfcOptrpt.getQuaQty());//合格数量
//            entryMap.put("FProcessFailQty",sfcOptrpt.getFailQty());//工废数量
//            entryMap.put("FMaterialFailQty",sfcOptrpt.getMaterialFailQty());//料废数量
            entryMap.put("FFinishQty",sfcOptrpt.getQuaQty());//完工数量
            FEntity.add(entryMap);
//        }
        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "SFC_OperationReport", updateParam);
            vtuzxKingdeeService.submit(client, "SFC_OperationReport", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "SFC_OperationReport", "0", optrptNo, "STK_InvCheckResult");
            sfcOptrpt.setKingdeeReport(optrptNo);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void syncPrdInsStock(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> detailList) throws Exception {
        //通过工序汇报单下推生产入库，然后保存入库单
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据汇报单号查询金蝶汇报单用于下推(汇报单号存在金蝶明细中的备注)
        String reportNo = prdInstock.getREPORTNO();//中台汇报单号

        String floatCond = String.format("FOptRemark  = '%s'", reportNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                "FEntity_FENTRYID",//末序汇报entryid
                "FBILLNO"
        ), floatCond);
        String FBILLNO = "";//末序汇报entryid
        if (!VtuzxUtil.isEmpty(planList)){
            FBILLNO = VtuzxUtil.getString(planList.get(0),"FBILLNO");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers",FBILLNO);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "SFC_OPTRPT2INSTOCK");//转换规则内码
//        model.put("RuleId", "1f4f462d-8810-4a5d-ae9d-5a684200abfc");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //工序汇报单下推生产入库单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationReport", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的入库单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的入库单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(idList.size() - 1);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDate", DateUtils.dateToStr(prdInstock.getFDATE(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台生产入库单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //中台汇报完到入库时一条数据，金蝶下推后，报废的数量也会占一条数据，
        for (PrdInstockDetail prdInstockDetail : detailList ){
            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FRealQty",prdInstockDetail.getFREALQTY());//实收数量
            entryMap.put("FLot",new Document("FNumber",prdInstockDetail.getFLOT()));
            entryMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber",prdInstockDetail.getFLOCATIONNUMBER())));;
            FEntity.add(entryMap);
        }
        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_INSTOCK", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void syncPrdInsStockSM(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> detailList) throws Exception {
        //通过工序汇报单下推生产入库，然后保存入库单
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据汇报单号查询金蝶汇报单用于下推(汇报单号存在金蝶明细中的备注)
        String reportNo = prdInstock.getREPORTNO();//中台汇报单号

        String floatCond = String.format("FDescription  = '%s'", reportNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                "FEntity_FENTRYID",//末序汇报entryid
                "FBILLNO"
        ), floatCond);
        String FBILLNO = "";//末序汇报entryid
        if (!VtuzxUtil.isEmpty(planList)){
            FBILLNO = VtuzxUtil.getString(planList.get(0),"FBILLNO");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers",FBILLNO);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "SFC_OPTRPT2INSTOCK");//转换规则内码
//        model.put("RuleId", "1f4f462d-8810-4a5d-ae9d-5a684200abfc");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //工序汇报单下推生产入库单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationReport", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的入库单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的入库单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(idList.size() -1);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDate", DateUtils.dateToStr(prdInstock.getFDATE(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台生产入库单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //中台汇报完到入库时一条数据，金蝶下推后，报废的数量也会占一条数据，
        for (PrdInstockDetail prdInstockDetail : detailList ){
            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FLOT",new Document("FNumber",prdInstockDetail.getFLOT()));//批号
            entryMap.put("FRealQty",prdInstockDetail.getFREALQTY());//实收数量
            FEntity.add(entryMap);
        }
        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_INSTOCK", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void syncPrdInsStockPackage(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> detailList, SfcOptrptPackage sfcOptrptPackage) throws Exception {
        //通过工序汇报单下推生产入库，然后保存入库单
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据汇报单号查询金蝶汇报单用于下推(汇报单号存在金蝶明细中的备注)
        String reportNo = prdInstock.getREPORTNO();//中台汇报单号

        String floatCond = String.format("FDescription  = '%s'", reportNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                "FEntity_FENTRYID",//末序汇报entryid
                "FBILLNO"
        ), floatCond);
        String FBILLNO = "";//末序汇报entryid
        if (!VtuzxUtil.isEmpty(planList)){
            FBILLNO = VtuzxUtil.getString(planList.get(0),"FBILLNO");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers",FBILLNO);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "SFC_OPTRPT2INSTOCK");//转换规则内码
//        model.put("RuleId", "1f4f462d-8810-4a5d-ae9d-5a684200abfc");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //工序汇报单下推生产入库单
        List<VtuzxMap> optrptList = new ArrayList<>();
        try {
            optrptList = vtuzxKingdeeService.push(client, "SFC_OperationReport", model);
        } catch (Exception e){
            _logger.info(e.getMessage());
        }
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的入库单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的入库单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(idList.size() -1);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDate",  DateUtils.dateToStr(sfcOptrptPackage.getFDate(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台生产入库单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //中台汇报完到入库时一条数据，金蝶下推后，报废的数量也会占一条数据，
        for (PrdInstockDetail prdInstockDetail : detailList ){
            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FLOT",new Document("FNumber",prdInstockDetail.getFLOT()));//批号
            entryMap.put("FRealQty",prdInstockDetail.getFREALQTY());//实收数量
            FEntity.add(entryMap);
        }
        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_INSTOCK", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", optrptNo, "STK_InvCheckResult");
            sfcOptrptPackage.setKingdeeInNo(optrptNo);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());

        }
    }

    @Override
    public void syncPrdReportJiJia(Long user_id, String proplanno,String trayNo) throws Exception {
        //根据托托盘号查询汇报单外层获取当前托盘的汇报信息，根据工序号排序
        //整理成map,key是工序号val是汇报单外层集合
        //循环map,创建工序汇报单
        List<SfcOptrpt> sfcOptrptList = sfcOptrptDao.selectList(new LambdaQueryWrapper<SfcOptrpt>()
                .eq(SfcOptrpt::getErpBillNo, proplanno)
                .eq(SfcOptrpt::getTrayNo, trayNo)
                .orderByAsc(SfcOptrpt::getOperpNo));
        Map<String,Object> optrptMap = new LinkedHashMap<>();//key是工序号val是汇报单外层集合
        for (SfcOptrpt sfcOptrpt : sfcOptrptList){
            Long operpNo = sfcOptrpt.getOperpNo();//工序号
            String operNoStr = operpNo.toString();//改成string
            List<SfcOptrpt> opList = (List<SfcOptrpt>) VtuzxUtil.getObject(optrptMap,operNoStr);
            if (!VtuzxUtil.isEmpty(opList)){//如果当前map集合有当前工序的信息
                opList.add(sfcOptrpt);
                optrptMap.put(operNoStr,opList);
            } else {//如果当前工序没有信息
                List<SfcOptrpt> optrpts = new ArrayList<>();
                optrpts.add(sfcOptrpt);
                optrptMap.put(operNoStr,optrpts);
            }
        }


        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        SfcOptrpt sfcOptrptOrder = sfcOptrptList.get(0);
        //根据工序单号和工序查询工序计划的entryid,用于下推
        String erpBillNo = sfcOptrptOrder.getErpBillNo();//工序计划单号
        Long operpNo = sfcOptrptOrder.getOperpNo();//工序号

        //工序计划下推工序汇报
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", erpBillNo);//单据编码集合
        model.put("EntryIds", "");//分录内码
//        model.put("RuleId", "82ddfcf2-199a-4e82-8fc7-2efc4fad532e");//转换规则内码
        model.put("RuleId", "SFC_OPRTPLAN2OPTRRPT");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推工序汇报单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationPlanning", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的汇报单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的汇报单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        Map<String,Object> optrDetailMap = new HashMap<>();//key:工序号,value需要传到金蝶的汇报数量
        for (Map.Entry entry : optrptMap.entrySet()) {
            String operNo = (String) entry.getKey();//工序号
            List<SfcOptrpt> dataList = (List<SfcOptrpt>) entry.getValue();
//            Map<String,Object> optQtyMap = new HashMap<>();//key:工序号 val:合格数量，废料数量(map)

            for (SfcOptrpt sfcOptrpt : dataList){
                String billNo = sfcOptrpt.getBillNo();
                SfcOptrptDetail sfcOptrptDetail = sfcOptrptDetailDao.selectOne(new LambdaQueryWrapper<SfcOptrptDetail>()
                        .eq(SfcOptrptDetail::getBillNo, billNo));
                VtuzxMap qtyMap = VtuzxUtil.getObject(optrDetailMap,operNo);
//                for (SfcOptrptDetail sfcOptrptDetail : sfcOptrptDetails ){
                    Double quaQty = sfcOptrptDetail.getQuaQty();//合格数量
                    Double processFailQty = sfcOptrptDetail.getProcessFailQty();//工费
                    Double materialFailQty = sfcOptrptDetail.getMaterialFailQty();//料废数量
                    Double endQty = sfcOptrptDetail.getEndQty();//完工数量
                    if (!VtuzxUtil.isEmpty(qtyMap)){
                        qtyMap.append("quaQty",VtuzxUtil.getDouble(qtyMap,"quaQty") + quaQty)
                                .append("processFailQty",VtuzxUtil.getDouble(qtyMap,"processFailQty") + processFailQty)
                                .append("billNo",billNo)
                                .append("materialFailQty",VtuzxUtil.getDouble(qtyMap,"materialFailQty") + materialFailQty)
                                .append("endQty",VtuzxUtil.getDouble(qtyMap,"endQty") + endQty);
                    } else {
                        qtyMap = new VtuzxMap();
                        qtyMap.append("quaQty",quaQty)
                                .append("processFailQty",processFailQty)
                                .append("billNo",billNo)
                                .append("materialFailQty", materialFailQty)
                                .append("endQty", endQty);
                    }
                    optrDetailMap.put(operNo,qtyMap);
//                }
            }


        }
        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDescription", erpBillNo);//备注暂时存工序号
        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //循环map集合添加明细信息
        for (Map.Entry entry : optrptMap.entrySet()) {
            String operNo = (String) entry.getKey();//工序号
            VtuzxMap qtyMap = VtuzxUtil.getObject(optrDetailMap,operNo);
            //查询明细id
            String floatCond = String.format("fbillno = '%s' and FOperNumber  = '%s'", optrptNo,operNo);
            List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                    "FEntity_FENTRYID"//分录id
            ), floatCond);
            String entryID = "";
            if (!VtuzxUtil.isEmpty(planList)){
                entryID = VtuzxUtil.getString(planList.get(0),"FEntity_FENTRYID");
            }
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FOperNumber",operNo);//工序号
            entryMap.put("FENTRYID",entryID);//实体主键
            entryMap.put("FQuaQty",VtuzxUtil.getDouble(qtyMap,"quaQty"));//合格数量
            entryMap.put("FProcessFailQty",VtuzxUtil.getDouble(qtyMap,"processFailQty"));//工废数量
            entryMap.put("FMaterialFailQty",VtuzxUtil.getDouble(qtyMap,"materialFailQty"));//料废数量
            entryMap.put("FFinishQty",VtuzxUtil.getDouble(qtyMap,"endQty"));//完工数量
            entryMap.put("FOptRemark",VtuzxUtil.getString(qtyMap,"billNo"));//工序汇报备注，用于下推入库单
            FEntity.add(entryMap);

//            List<SfcOptrpt> dataList = (List<SfcOptrpt>) entry.getValue();
//            for (SfcOptrpt sfcOptrpt : dataList){
//                String billNo = sfcOptrpt.getBillNo();
//                List<SfcOptrptDetail> sfcOptrptDetails = sfcOptrptDetailDao.selectList(new LambdaQueryWrapper<SfcOptrptDetail>()
//                        .eq(SfcOptrptDetail::getBillNo, billNo));
//                for (SfcOptrptDetail sfcOptrptDetail : sfcOptrptDetails ){
//                    //查询明细id
//                    String floatCond = String.format("fbillno = '%s' and FOperNumber  = '%s'", optrptNo,operNo);
//                    List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
//                            "FEntity_FENTRYID"//分录id
//                    ), floatCond);
//                    String entryID = "";
//                    if (!VtuzxUtil.isEmpty(planList)){
//                        entryID = VtuzxUtil.getString(planList.get(0),"FEntity_FENTRYID");
//                    }
//                    Map<String, Object> entryMap = new LinkedHashMap<>();
//                    entryMap.put("FOperNumber",operNo);//工序号
//                    entryMap.put("FENTRYID",entryID);//实体主键
//                    entryMap.put("FQuaQty",sfcOptrptDetail.getQuaQty());//合格数量
//                    entryMap.put("FProcessFailQty",sfcOptrptDetail.getProcessFailQty());//工废数量
//                    entryMap.put("FMaterialFailQty",sfcOptrptDetail.getMaterialFailQty());//料废数量
//                    entryMap.put("FFinishQty",sfcOptrptDetail.getEndQty());//完工数量
//                    entryMap.put("FOptRemark",billNo);//工序汇报备注，用于下推入库单
//                    FEntity.add(entryMap);
//                }
//            }

        }


        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "SFC_OperationReport", updateParam);
            vtuzxKingdeeService.submit(client, "SFC_OperationReport", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "SFC_OperationReport", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void syncPrdReturn(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> prdInstockDetailList,Double failCount) throws Exception {
        //通过生产领料单下推退料单，然后补充数量信息
        String fbillnomo = prdInstock.getFBILLNOMO();//生产订单号
        String trayno = prdInstock.getTRAYNO();
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        PickDetail pickDetail = pickDetailDao.selectOne(new LambdaQueryWrapper<PickDetail>()
                .eq(PickDetail::getTRAYNO, trayno)
                .eq(PickDetail::getMOBILLNO, fbillnomo));
        String fbillno = pickDetail.getFBILLNO();
        if (VtuzxUtil.isEmpty(fbillno)){
            throw new RuntimeException("当前订单还未领料或者领料不成功,无法入库");
        }
        PrdPick prdPick = prdPickDao.selectOne(new LambdaQueryWrapper<PrdPick>()
                .eq(PrdPick::getFBILLNO, fbillno));
        String fkdbillno = prdPick.getFKDBILLNO();//金蝶领料单号

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", fkdbillno);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "PRD_PICKMTRL2RETURNMTRL");//转换规则内码
//        model.put("RuleId", "253429a0-3889-416c-a068-5b272f8712c0");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推生产退料
        List<VtuzxMap> returnList = vtuzxKingdeeService.push(client, "PRD_PickMtrl", model);
        VtuzxMap optrpt = returnList.get(0);
        String returnNo = VtuzxUtil.getString(optrpt,"Number");//下推后的退料单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的退料id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");
        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer returnEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", returnNo);
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台入库单号
        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //循环map集合添加明细信息

        for (PrdInstockDetail prdInstockDetail : prdInstockDetailList){
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FEntryID",returnEntryId);
//            entryMap.put("FMaterialId",new Document("FNUMBER",pickDetail.getFMATERIALNUMBER()));
//            entryMap.put("FLot",new Document("FNumber", pickDetail.getFLOT()));
            entryMap.put("FAPPQty",failCount);//申请数量
            entryMap.put("FQty",failCount);//实退数量
            entryMap.put("FStockId",new Document("FNUMBER","CK022"));//仓库是报废品仓库(不能作为回材)
            FEntity.add(entryMap);

        }


        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_ReturnMtrl", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_ReturnMtrl", "0", returnNo);
            vtuzxKingdeeService.audit(client, "PRD_ReturnMtrl", "0", returnNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 传金蝶退料(包材)
     * @param user_id
     * @param prdReturn
     * @param detailList
     * @throws Exception
     */
    @Override
    public void syncPrdReturnBao(Long user_id, PrdReturn prdReturn, List<PrdReturnDetail> detailList,String kingdeeNo,SfcOptrptPackage sfcOptrptPackage) throws Exception {
        //通过补料单下推退料单
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", kingdeeNo);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "PRD_FEEDMTRL2RETURNMTRL");//转换规则内码
//        model.put("RuleId", "253429a0-3889-416c-a068-5b272f8712c0");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推生产退料
        List<VtuzxMap> returnList = new ArrayList<>();
        try {
            returnList = vtuzxKingdeeService.push(client, "PRD_FeedMtrl", model);
        } catch (Exception e){

            throw new RuntimeException(e.getMessage());
        }
        VtuzxMap optrpt = returnList.get(0);
        String returnNo = VtuzxUtil.getString(optrpt,"Number");//下推后的退料单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的退料id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");
        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer returnEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", returnNo);
        updateModle.put("FDate", DateUtils.dateToStr(sfcOptrptPackage.getFDate(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FDescription", prdReturn.getFBILLNO());//备注暂时存中台入库单号
        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据
        //循环map集合添加明细信息

        for (PrdReturnDetail returnDetail : detailList){
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FEntryID",returnEntryId);
            entryMap.put("FAPPQty",returnDetail.getFACTQTY());//申请数量
            entryMap.put("FQty",returnDetail.getFACTQTY());//实退数量
            entryMap.put("FStockId",new Document("FNUMBER","CK022"));//仓库是报废品仓库(不能作为回材)
            FEntity.add(entryMap);

        }


        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_ReturnMtrl", updateParam);
            sfcOptrptPackage.setKingdeeReturn(returnNo);
//            vtuzxKingdeeService.submit(client, "PRD_ReturnMtrl", "0", returnNo);
//            vtuzxKingdeeService.audit(client, "PRD_ReturnMtrl", "0", returnNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void syncPrdInsStockHuiCai(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> prdInstockDetailList, double failCount) throws Exception {
        //通过工序汇报单下推生产入库，然后保存入库单
        //报废数量需要通过单据编号下推，要不然有数量校验无法保存入库
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据汇报单号查询金蝶汇报单用于下推(汇报单号存在金蝶明细中的备注)
        String reportNo = prdInstock.getREPORTNO();//中台汇报单号

        String floatCond = String.format("FOptRemark = '%s'", reportNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                "FEntity_FENTRYID",//末序汇报entryid
                "FBILLNO"
        ), floatCond);
        String FBILLNO = "";//末序汇报entryid
        if (!VtuzxUtil.isEmpty(planList)){
            FBILLNO = VtuzxUtil.getString(planList.get(0),"FBILLNO");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers",FBILLNO);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "SFC_OPTRPT2INSTOCK");//转换规则内码
//        model.put("RuleId", "1f4f462d-8810-4a5d-ae9d-5a684200abfc");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //工序汇报单下推生产入库单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationReport", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的入库单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的入库单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台生产入库单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据

            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FENTRYID",optEntryId);//实体主键
            entryMap.put("FMustQty",failCount);//实收数量
            entryMap.put("FRealQty",failCount);//实收数量
            entryMap.put("FStockId",new Document("FNUMBER","CK023"));//实收数量
            entryMap.put("FLot",new Document("FNUMBER",prdInstockDetailList.get(0).getFLOT()));//批号
            FEntity.add(entryMap);

        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_INSTOCK", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 包装间传金蝶补料单
     * @param user_id
     * @param detailList
     * @throws Exception
     */
    @Override
    public String syncprdfeed(Long user_id, PrdFeed prdFeed,List<PrdFeedDetail> detailList,SfcOptrptPackage sfcOptrptPackage) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e){
            throw new RuntimeException("金蝶账号密码错误请维护");
        }
        String fbillnomo = prdFeed.getFBILLNOMO();//生产订单号

        String materialNo = detailList.get(0).getFMATERIALNUMBER();
        //查询用料清单编号
        PpBom ppBom = ppBomDao.selectOne(new LambdaQueryWrapper<PpBom>().eq(PpBom::getFMOBILLNO, fbillnomo)
                .eq(PpBom::getFMATERIALNUMBER,materialNo));
        String ppbomNo = ppBom.getFBILLNO();//用料清单单据编号
        //用料清单下推补料单
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers", ppbomNo);//单据编码集合
        model.put("EntryIds", "");//分录内码
//        model.put("RuleId", "ebd2a7c0-d2e3-423a-af80-1069d36af235");//转换规则内码
        model.put("RuleId", "PRD_PPBOM2FEEDMTRL");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //下推生产补料单
        List<VtuzxMap> optrptList = new ArrayList<>();
        try {
            optrptList = vtuzxKingdeeService.push(client, "PRD_PPBOM", model);
        } catch (Exception e){

            throw new RuntimeException(e.getMessage());
        }
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的补料单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的汇报单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDate", DateUtils.dateToStr(sfcOptrptPackage.getFDate(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FSTOCKERID", new VtuzxMap("FNAME","王英爽"));
        updateModle.put("F_VKFP_CheckBox_23p", true);
        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据

        //查询即时库存获取批号和生产日期
        List<VtuzxMap> inventoryList = vtuzxKingdeeService.getInventoryBymaterialPackage(user_id, materialNo);
        Double finfactqty = detailList.get(0).getFACTUALQTY();//需求数量

        //判断数量够不够扣
        for (VtuzxMap data : inventoryList){
            Map<String, Object> entryMap = new LinkedHashMap<>();
            Double baseQty = VtuzxUtil.getDouble(data,"FBASEQTY");
            if (baseQty >= finfactqty){//如果够扣的话
                entryMap.put("FENTRYID",optEntryId);//实体主键
                entryMap.put("FAppQty",finfactqty);//申请数量
                entryMap.put("FActualQty",finfactqty);//实发数量
                entryMap.put("FBaseActualQty",finfactqty);//基本单位实发数量
                entryMap.put("FBaseStockActualQty",finfactqty);//基本单位实发数量
                entryMap.put("FStockId",new Document("FNUMBER","CK020"));//仓库
                entryMap.put("FLot",new Document("FNUMBER",VtuzxUtil.getString(data,"FLot.fname")));//批号
                entryMap.put("FProduceDate",VtuzxUtil.getString(data,"FProduceDate"));//生产日期
                FEntity.add(entryMap);
                break;
            } else {
                entryMap.put("FENTRYID",optEntryId);//实体主键
                entryMap.put("FAppQty",baseQty);//申请数量
                entryMap.put("FActualQty",baseQty);//实发数量
                entryMap.put("FBaseActualQty",baseQty);//基本单位实发数量
                entryMap.put("FBaseStockActualQty",baseQty);//基本单位实发数量
                entryMap.put("FStockId",new Document("FNUMBER","CK023"));//仓库
                entryMap.put("FLot",new Document("FNUMBER",VtuzxUtil.getString(data,"FLot.fname")));//批号
                entryMap.put("FProduceDate",VtuzxUtil.getString(data,"FProduceDate"));//生产日期
                FEntity.add(entryMap);
                finfactqty-=baseQty;
            }
        }




        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_FeedMtrl", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_FeedMtrl", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_FeedMtrl", "0", optrptNo, "STK_InvCheckResult");
            sfcOptrptPackage.setKingdeeFeedNo(optrptNo);
        } catch (Exception e){

            throw new RuntimeException(e.getMessage());
        }
        return optrptNo;

    }

    /**
     * 根据物料编码查询库存信息
     * @param user_id
     * @param materialNo
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getInventoryByNo(Long user_id, String materialNo) throws Exception {

        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("FMaterialId.FNUMBER");//物料编码
        arrayList.add("FMaterialId.FName");//物料名称
        arrayList.add("FLot.fname");//批号
        arrayList.add("FBASEQTY");//库存基本数量
        arrayList.add("FStockId.FNUMBER");//仓库编码
        arrayList.add("FStockName");//仓库名称
        arrayList.add("FStockLocId.FF100001.FNUmber");//仓位编码
        arrayList.add("FStockLocId.FF100001.FNAME");//仓位名称
        String cond = String.format("FMaterialId.FNUMBER = '%s'  and FBASEQTY > 0",materialNo);
        List<VtuzxMap> bomQuery = vtuzxKingdeeService.query(client, "STK_Inventory", arrayList,
                cond, "FID", 0, 0);
        if(VtuzxUtil.isEmpty(bomQuery)){
            throw new Exception("当前物料没有库存");
        }
        List<VtuzxMap> resList = new ArrayList<>();
        for (VtuzxMap data : bomQuery){
            String fmaterialNo = VtuzxUtil.getString(data,"FMaterialId.FNUMBER");//物料编码
            String fmaterialName = VtuzxUtil.getString(data,"FMaterialId.FName");//物料名称
            Integer forgId = VtuzxUtil.getInt(data,"FStockOrgId.FNumber");//组织编码
            String forgName = VtuzxUtil.getString(data,"FStockOrgId.FNAME");//组织名称
            String batchNo = VtuzxUtil.getString(data,"FLot.fname");//批号
            String stockNo = VtuzxUtil.getString(data,"FStockId.FNUMBER");//仓库编码
            String stockName = VtuzxUtil.getString(data,"FStockName");//仓库名称
            double FBASEQTY = VtuzxUtil.getDouble(data,"FBASEQTY");//库存基本数量

            String locationName = VtuzxUtil.getString(data,"FStockLocId.FF100001.FNAME");//获取仓位名称
            String locationNo = VtuzxUtil.getString(data,"FStockLocId.FF100001.FNUMBER");//获取仓位名称
            //返回给后端的数据，现在查询出来的字段信息带.前端无法识别
            VtuzxMap dataMap = new VtuzxMap();
            dataMap.append("fmaterialNo",fmaterialNo)
                    .append("fmaterialName",fmaterialName)
                    .append("forgId",forgId)
                    .append("forgName",forgName)
                    .append("batchNo",batchNo)
                    .append("stockNo",stockNo)
                    .append("stockName",stockName)
                    .append("FBASEQTY",FBASEQTY)
                    .append("locationNo",locationNo)
                    .append("locationName",locationName);


            resList.add(dataMap);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",resList);

        return data;
    }

    /**
     * 调拨单传金蝶(调拨申请)
     * @param user_id
     * @param stkTransfer
     * @param stkTransferDetailList
     * @throws Exception
     */
    @Override
    public void syncTransfer(Long user_id, StkTransfer stkTransfer, List<StkTransferDetail> stkTransferDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }

        Map<String, Object> param = new LinkedHashMap<>();
        List<Map<String, Object>> stockTransferEntryList = new ArrayList<>();//存放单据体数据
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID",new VtuzxMap("FNUMBER","ZJDB01_SYS"));//单据类型
        model.put("FBizType","NORMAL");//业务类型
        model.put("FTransferDirect","GENERAL");//调拨方向
        model.put("FTransferBizType","InnerOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber","100"));//结算组织
        model.put("FSaleOrgId",new VtuzxMap("FNumber","100"));//销售组织
        model.put("FStockOutOrgId",new VtuzxMap("FNumber","100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead",new VtuzxMap("FNumber","100"));//调出货主
        model.put("FStockOrgId",new VtuzxMap("FNumber","100"));//调入库存组织
        model.put("FIsIncludedTax",true);//是否含税
        model.put("FIsPriceExcludeTax",true);//价外税
        model.put("FExchangeTypeId",new VtuzxMap("FNUMBER","HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
        model.put("FDate", VtuzxUtil.formatYmdHmsF(stkTransfer.getFDATE()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FNote", stkTransfer.getFBillNo());
//        model.put("FWriteOffConsign",false);//冲减普通寄售调拔单结算数量

        //单据体数据
        for (StkTransferDetail detaill : stkTransferDetailList){
            String materialNo  = detaill.getFMATERIALNUMBER();
            Integer transferAppId = detaill.getTransferAppId();
            //查询调拨申请的fid,fentryid
//            StkTransferAppDetaill stkTransferAppDetaill = stkTransferAppDetailDao.selectById(transferAppId);
            //判断是否启用批号,查询辅助单位
            String floatCond = String.format("FNumber = '%s'", materialNo);
            List<VtuzxMap> bd_Material = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage",
                    "FBaseUnitId",
                    "FIsKFPeriod",
                    "FAuxUnitID.fnumber"//辅助单位
            ), floatCond);
            boolean FIsBatchManage = true;//是否启用批号
            boolean FIsKFPeriod = true;//是否启用保质期

            String FAuxUnitID = "";
            if (bd_Material != null && bd_Material.size() > 0) {
                FIsBatchManage = bd_Material.get(0).getBoolean("FIsBatchManage");
                FIsKFPeriod = bd_Material.get(0).getBoolean("FIsKFPeriod");
                FAuxUnitID = bd_Material.get(0).getString("FAuxUnitID.fnumber");
            }

            Map<String, Object> stockTransferEntry = new LinkedHashMap<>();
            stockTransferEntry.put("FMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FUnitID", new VtuzxMap("FNumber", detaill.getFUNITID()));
            stockTransferEntry.put("FQty", detaill.getFQTY());//数量
            if (FIsBatchManage){
                stockTransferEntry.put("FLot", new VtuzxMap("FNumber", detaill.getFLOT()));
            }
            if (FIsKFPeriod){
                stockTransferEntry.put("FProduceDate", DateUtils.dateToStr(detaill.getProductionDate(),"yyyy-MM-dd" +  " 00:00:00"));//生产日期
            }

            stockTransferEntry.put("FSrcStockId", new VtuzxMap("FNumber", detaill.getFSrcStockId()));//调出仓库
            stockTransferEntry.put("FSrcStockLocId",new Document("FSRCSTOCKLOCID__FF100001", new Document("FNumber",detaill.getFSrcStockLocId())));
            stockTransferEntry.put("FDestStockId", new VtuzxMap("FNumber", detaill.getFDestStockId()));//调入仓库
            if(!VtuzxUtil.isEmpty(detaill.getFDestStockLocId())){
                stockTransferEntry.put("FDestStockLocId",new Document("FDESTSTOCKLOCID__FF100001", new Document("FNumber",detaill.getFDestStockLocId())));
            }

            stockTransferEntry.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            stockTransferEntry.put("FOwnerTypeOutId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FOwnerTypeId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FSecUnitId", new VtuzxMap("FNumber", FAuxUnitID));//库存辅助单位
            stockTransferEntry.put("FBaseUnitId", new VtuzxMap("FNumber", detaill.getFUNITID()));
            stockTransferEntry.put("FBaseQty", detaill.getFQTY());
            stockTransferEntry.put("FISFREE", false);
            stockTransferEntry.put("FKeeperTypeId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FKeeperTypeOutId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            if (FIsBatchManage){
                stockTransferEntry.put("FDestLot", new VtuzxMap("FNumber", detaill.getFLOT()));
            }
            stockTransferEntry.put("FDestMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FSaleUnitId", new VtuzxMap("FNumber", detaill.getFUNITID()));
//            stockTransferEntry.put("FPriceUnitID", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FTransReserveLink", false);
            stockTransferEntry.put("FCheckDelivery", false);
            //添加linked信息(收料通知单关联)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FBillEntry_Link_FRuleId", "StkTransferApply-StkTransferDirect");//下推规则
            linkMap.put("FBillEntry_Link_FSTABLENAME", "T_STK_STKTRANSFERAPPENTRY");//关联表名
            linkMap.put("FBillEntry_Link_FSBILLID",detaill.getTransferAppId());//源单内码
            linkMap.put("FBillEntry_Link_FSID", detaill.getTransferAppDetailId());// 源单分录内码
            linkList.add(linkMap);
            stockTransferEntry.put("FBillEntry_Link", linkList);

            stockTransferEntryList.add(stockTransferEntry);


        }
        model.put("FBillEntry",stockTransferEntryList);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField",false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag","");
        param.put("IsControlPrecision",false);
        param.put("ValidateRepeatJson",false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = vtuzxKingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            stkTransfer.setFKDBILLNO(number);
            vtuzxKingdeeService.submit(client, "STK_TransferDirect", "0", number);
            vtuzxKingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
        } catch (Exception e){
            _logger.info(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 直接调拨传金蝶
     * @param user_id
     * @param stkTransfer
     * @param stkTransferDetailList
     * @throws Exception
     */
    @Override
    public void syncTransferAllocation(Long user_id, StkTransfer stkTransfer, List<StkTransferDetail> stkTransferDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }

        Map<String, Object> param = new LinkedHashMap<>();
        List<Map<String, Object>> stockTransferEntryList = new ArrayList<>();//存放单据体数据
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID",new VtuzxMap("FNUMBER","ZJDB01_SYS"));//单据类型
        model.put("FBizType","NORMAL");//业务类型
        model.put("FTransferDirect","GENERAL");//调拨方向
        model.put("FTransferBizType","InnerOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber","100"));//结算组织
        model.put("FSaleOrgId",new VtuzxMap("FNumber","100"));//销售组织
        model.put("FStockOutOrgId",new VtuzxMap("FNumber","100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead",new VtuzxMap("FNumber","100"));//调出货主
        model.put("FStockOrgId",new VtuzxMap("FNumber","100"));//调入库存组织
        model.put("FIsIncludedTax",true);//是否含税
        model.put("FIsPriceExcludeTax",true);//价外税
        model.put("FExchangeTypeId",new VtuzxMap("FNUMBER","HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
        model.put("FDate", VtuzxUtil.formatYmdHmsF(stkTransfer.getFDATE()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FNote", stkTransfer.getFBillNo());
//        model.put("FWriteOffConsign",false);//冲减普通寄售调拔单结算数量

        //单据体数据
        for (StkTransferDetail detaill : stkTransferDetailList){
            String materialNo  = detaill.getFMATERIALNUMBER();
            Integer transferAppId = detaill.getTransferAppId();
            //查询调拨申请的fid,fentryid
            StkTransferAppDetaill stkTransferAppDetaill = stkTransferAppDetailDao.selectById(transferAppId);
            //判断是否启用批号,查询辅助单位
            String floatCond = String.format("FNumber = '%s'", materialNo);
            List<VtuzxMap> bd_Material = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage",
                    "FBaseUnitId",
                    "FIsKFPeriod",
                    "FAuxUnitID.fnumber"//辅助单位
            ), floatCond);
            boolean FIsBatchManage = true;//是否启用批号
            boolean FIsKFPeriod = true;//是否启用保质期

            String FAuxUnitID = "";
            if (bd_Material != null && bd_Material.size() > 0) {
                FIsBatchManage = bd_Material.get(0).getBoolean("FIsBatchManage");
                FAuxUnitID = bd_Material.get(0).getString("FAuxUnitID.fnumber");
                FIsKFPeriod = bd_Material.get(0).getBoolean("FIsKFPeriod");
            }

            Map<String, Object> stockTransferEntry = new LinkedHashMap<>();
            stockTransferEntry.put("FMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FUnitID", new VtuzxMap("FNumber", detaill.getFUNITID()));
            stockTransferEntry.put("FQty", detaill.getFQTY());//数量
            if (FIsBatchManage){
                stockTransferEntry.put("FLot", new VtuzxMap("FNumber", detaill.getFLOT()));
            }
            if (FIsKFPeriod){
                stockTransferEntry.put("FProduceDate", DateUtils.dateToStr(detaill.getProductionDate(),"yyyy-MM-dd" +  " 00:00:00"));//生产日期
            }

            stockTransferEntry.put("FSrcStockId", new VtuzxMap("FNumber", detaill.getFSrcStockId()));//调出仓库
            stockTransferEntry.put("FSrcStockLocId",new Document("FSRCSTOCKLOCID__FF100001", new Document("FNumber",detaill.getFSrcStockLocId())));
            stockTransferEntry.put("FDestStockId", new VtuzxMap("FNumber", detaill.getFDestStockId()));//调入仓库
            if(!VtuzxUtil.isEmpty(detaill.getFDestStockLocId())){
                stockTransferEntry.put("FDestStockLocId",new Document("FDESTSTOCKLOCID__FF100001", new Document("FNumber",detaill.getFDestStockLocId())));
            }

            stockTransferEntry.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            stockTransferEntry.put("FOwnerTypeOutId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FOwnerTypeId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FSecUnitId", new VtuzxMap("FNumber", FAuxUnitID));//库存辅助单位
            stockTransferEntry.put("FBaseUnitId", new VtuzxMap("FNumber", detaill.getFUNITID()));
            stockTransferEntry.put("FBaseQty", detaill.getFQTY());
            stockTransferEntry.put("FISFREE", false);
            stockTransferEntry.put("FKeeperTypeId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FKeeperTypeOutId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            if (FIsBatchManage){
                stockTransferEntry.put("FDestLot", new VtuzxMap("FNumber", detaill.getFLOT()));
            }
            stockTransferEntry.put("FDestMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FSaleUnitId", new VtuzxMap("FNumber", detaill.getFUNITID()));
//            stockTransferEntry.put("FPriceUnitID", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FTransReserveLink", false);
            stockTransferEntry.put("FCheckDelivery", false);
            stockTransferEntryList.add(stockTransferEntry);


        }
        model.put("FBillEntry",stockTransferEntryList);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField",false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag","");
        param.put("IsControlPrecision",false);
        param.put("ValidateRepeatJson",false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = vtuzxKingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            stkTransfer.setFKDBILLNO(number);
            vtuzxKingdeeService.submit(client, "STK_TransferDirect", "0", number);
            vtuzxKingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
        } catch (Exception e){
            _logger.info(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 包装间传金蝶领料单
     * @param user_id
     * @param prdPick
     * @param detailList
     * @throws Exception
     */
    @Override
    public void syncPrdPickBao(Long user_id, PrdPick prdPick, List<PickDetail> detailList,SfcOptrptPackage sfcOptrptPackage) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e){
            throw new RuntimeException("金蝶账号密码错误请维护");
        }
        String fbillnomo = prdPick.getFBILLNOMO();//生产订单号
        String materialNo = detailList.get(0).getFMATERIALNUMBER();
        Map<String, Object> pickModel = new LinkedHashMap<>();//金蝶领料单model
        pickModel.put("FID",0);//实体主键
        pickModel.put("FBillType",new VtuzxMap("FNUMBER","SCLLD01_SYS"));//单据类型
        pickModel.put("FDate", DateUtils.dateToStr(sfcOptrptPackage.getFDate(),"yyyy-MM-dd HH:mm:ss"));//单据日期
        pickModel.put("FStockOrgId",new VtuzxMap("FNUMBER","100"));//发料组织
        pickModel.put("FPrdOrgId",new VtuzxMap("FNUMBER","100"));//生产组织
        pickModel.put("FWorkShopId",new VtuzxMap("FNUMBER","BZ"));//车间默认机加车间
        pickModel.put("FSTOCKERID",new VtuzxMap("FNAME","王英爽"));//仓管员
        pickModel.put("FDescription",prdPick.getFBILLNO());//中台补料单号
        List<Map<String,Object>> FEntity  = new ArrayList<>();//明细信息
        SfcProplan sfcProplan = sfcProplanDao.selectOne(new LambdaQueryWrapper<SfcProplan>()
                .eq(SfcProplan::getMoBillNo, fbillnomo).last("limit 1"));
        //查询用料清单编号
        PpBom ppBom = ppBomDao.selectOne(new LambdaQueryWrapper<PpBom>().eq(PpBom::getFMOBILLNO, fbillnomo)
                .eq(PpBom::getFMATERIALNUMBER,materialNo));
        String ppbomNo = ppBom.getFBILLNO();//用料清单单据编号
        //查询即时库存获取批号和生产日期
        List<VtuzxMap> inventoryList = vtuzxKingdeeService.getInventoryBymaterialPackage(user_id, materialNo);
        Double finfactqty = detailList.get(0).getFINFACTQTY();//需求数量
        //查询库存辅助单位
        String FStockUnitId = "";
        List<VtuzxMap> unitQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FAuxUnitID.fnumber"
                ),
                String.format("FNUMBER = '%s'",materialNo ), null, 0, 1);
        if (!VtuzxUtil.isEmpty(unitQuery)) {
            FStockUnitId = VtuzxUtil.getString(unitQuery.get(0),"FAuxUnitID.fnumber");//辅助单位
        }
        //查询用料清单获取
        String FId = "";//原单内码
        String FEntryId = "";//分录内码
        //查询原单内码和分录内码
        List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "PRD_PPBOM", new VtuzxArrayList<>(
                        "FId",
                        "FEntity_FEntryID"//分录内码
                ),
                String.format("FBillNo = '%s' and FMaterialId2.FNumber = '%s'", ppbomNo,materialNo), null, 0, 1);
        if (!VtuzxUtil.isEmpty(prdInQuery)) {
            FId = VtuzxUtil.getString(prdInQuery.get(0),"FId");
            FEntryId = VtuzxUtil.getString(prdInQuery.get(0),"FEntity_FEntryID");
        }
        //查询生产订单内码
        String moEntryId = "";
        List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MO", new VtuzxArrayList<>(
                        "FTreeEntity_FEntryID"

                ),
                String.format("FBillNo = '%s'", fbillnomo), null, 0, 1);

        if (!VtuzxUtil.isEmpty(moQuery)) {
            moEntryId = VtuzxUtil.getString(moQuery.get(0),"FTreeEntity_FEntryID");//生产订单分录内码
        }

        for (VtuzxMap data : inventoryList){
            Double baseQty = VtuzxUtil.getDouble(data,"FBASEQTY");
            if (baseQty >= finfactqty) {//如果够扣的话
                Map<String,Object> entity = new LinkedHashMap<>();//金蝶明细信息
                entity.put("FParentMaterialId",new VtuzxMap("FNumber",sfcProplan.getMaterialNo()));//物料编码
                entity.put("FMaterialId",new VtuzxMap("FNumber",materialNo));//物料编码
                //这个物料编码是订单上的物料编码
                entity.put("FUnitID",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//基本单位
                entity.put("FAppQty",finfactqty);//申请数量
                entity.put("FActualQty",finfactqty);//实发数量
                entity.put("FStockId",new VtuzxMap("FNumber","CK020"));//仓库默认毛坯库
                entity.put("FProduceDate",VtuzxUtil.getString(data,"FProduceDate"));//生产日期
                entity.put("FLot",new VtuzxMap("FNumber",VtuzxUtil.getString(data,"FLot.fname")));//批号
                entity.put("FMoBillNo",fbillnomo);//生产订单编号
                entity.put("FPPBomBillNo",ppbomNo);//用料清单编号
                entity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型

                entity.put("FBaseActualQty",finfactqty);//基本单位实发数量
                entity.put("FBaseStockActualQty",finfactqty);//基本单位实发数量
                entity.put("FEntryWorkShopId",new VtuzxMap("FNumber","BZ"));//车间

                entity.put("FBaseUnitId",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//基本单位

                entity.put("FStockUnitId",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//库存单位
                entity.put("FSecUnitId",new VtuzxMap("FNumber",FStockUnitId));//辅助单位


                entity.put("FOwnerId",new VtuzxMap("FNumber","100"));//货主
                entity.put("FParentOwnerTypeId","BD_OwnerOrg");//产品货主类型
                entity.put("FParentOwnerId",new VtuzxMap("FNumber","100"));//产品货主


                entity.put("FMoEntryId",moEntryId);//生产订单分录内码
                entity.put("FPPBomEntryId",FEntryId);//用料清单分录内码
                //添加link信息(用料清单关联)
                List<Map<String,Object>> linkList = new ArrayList<>();
                Map<String,Object> linkMap = new LinkedHashMap<>();
                linkMap.put("FEntity_Link_FRuleId","ea808801-aef0-84fd-11f0-830bdaa3b1e8");//下推规则
                //linkMap.put("FEntity_Link_FRuleId","3be192e7-0961-4236-90d2-c7c21263e307");//下推规则
                linkMap.put("FEntity_Link_FSTableName","T_PRD_PPBOMENTRY");//关联表名
                linkMap.put("FEntity_Link_FSBillId",FId);//源单内码
                linkMap.put("FEntity_Link_FSId",FEntryId);// 源单分录内码
                linkList.add(linkMap);
                entity.put("FEntity_Link",linkList);
                FEntity.add(entity);
                break;
            } else {
                Map<String,Object> entity = new LinkedHashMap<>();//金蝶明细信息
                entity.put("FParentMaterialId",new VtuzxMap("FNumber",sfcProplan.getMaterialNo()));//物料编码
                entity.put("FMaterialId",new VtuzxMap("FNumber",materialNo));//物料编码
                //这个物料编码是订单上的物料编码
                entity.put("FUnitID",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//基本单位
                entity.put("FAppQty",baseQty);//申请数量
                entity.put("FActualQty",baseQty);//实发数量
                entity.put("FStockId",new VtuzxMap("FNumber","CK020"));//仓库默认毛坯库
                entity.put("FProduceDate",VtuzxUtil.getString(data,"FProduceDate"));//生产日期
                entity.put("FLot",new VtuzxMap("FNumber",VtuzxUtil.getString(data,"FLot.fname")));//批号
                entity.put("FMoBillNo",fbillnomo);//生产订单编号
                entity.put("FPPBomBillNo",ppbomNo);//用料清单编号
                entity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型

                entity.put("FBaseActualQty",baseQty);//基本单位实发数量
                entity.put("FBaseStockActualQty",baseQty);//基本单位实发数量
                entity.put("FEntryWorkShopId",new VtuzxMap("FNumber","BZ"));//车间

                entity.put("FBaseUnitId",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//基本单位

                entity.put("FStockUnitId",new VtuzxMap("FNumber",detailList.get(0).getFUNITID()));//库存单位
                entity.put("FSecUnitId",new VtuzxMap("FNumber",FStockUnitId));//辅助单位
                entity.put("FOwnerId",new VtuzxMap("FNumber","100"));//货主
                entity.put("FParentOwnerTypeId","BD_OwnerOrg");//产品货主类型
                entity.put("FParentOwnerId",new VtuzxMap("FNumber","100"));//产品货主
                entity.put("FMoEntryId",moEntryId);//生产订单分录内码
                entity.put("FPPBomEntryId",FEntryId);//用料清单分录内码
                //添加link信息(用料清单关联)
                List<Map<String,Object>> linkList = new ArrayList<>();
                Map<String,Object> linkMap = new LinkedHashMap<>();
                linkMap.put("FEntity_Link_FRuleId","ea808801-aef0-84fd-11f0-830bdaa3b1e8");//下推规则
                //linkMap.put("FEntity_Link_FRuleId","3be192e7-0961-4236-90d2-c7c21263e307");//下推规则
                linkMap.put("FEntity_Link_FSTableName","T_PRD_PPBOMENTRY");//关联表名
                linkMap.put("FEntity_Link_FSBillId",FId);//源单内码
                linkMap.put("FEntity_Link_FSId",FEntryId);// 源单分录内码
                linkList.add(linkMap);
                entity.put("FEntity_Link",linkList);
                FEntity.add(entity);
                finfactqty -= baseQty;
            }
        }

        pickModel.put("FEntity",FEntity);
        Map<String,Object> param = new HashMap<>();//传单总参
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("InterationFlags", "");
        param.put("IsAutoAdjustField",true);
        param.put("Model", pickModel);
        try {
            List<VtuzxMap> pickList = vtuzxKingdeeService.save(client, "PRD_PickMtrl", param);
            VtuzxMap prdReturnMap = pickList.get(0);
            String number = VtuzxUtil.getString(prdReturnMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_PickMtrl", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_PickMtrl", "0", number, "STK_InvCheckResult");
            sfcOptrptPackage.setKingdeePickNo(number);
        } catch (Exception e){
           throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 根据件号和仓库查询库存
     * @param user_id
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getInventoryByItem(Long user_id, Map<String, Object> map) throws Exception {
        String itemnumber = VtuzxUtil.getString(map,"itemnumber");//件号
        String fstockNo = VtuzxUtil.getString(map,"stockNo");//件号
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("FMaterialId.FNUMBER");//物料编码
        arrayList.add("FMaterialId.FName");//物料名称
        arrayList.add("FMaterialId.FSPECIFICATION");//规格
        arrayList.add("FLot.fname");//批号
        arrayList.add("FBASEQTY");//库存基本数量
        arrayList.add("FStockId.FNUMBER");//仓库编码
        arrayList.add("FStockName");//仓库名称
        arrayList.add("FProduceDate");//仓库名称
        arrayList.add("FStockLocId.FF100001.FNUmber");//仓位编码
        arrayList.add("FStockLocId.FF100001.FNAME");//仓位名称
        String cond = "";
        if (!VtuzxUtil.isEmpty(fstockNo)){
            cond = String.format("FMaterialId.FSPECIFICATION like '%s' and FStockId.FNUMBER = '%s'  and FBASEQTY > 0",itemnumber  + "%",fstockNo);
        } else {
            cond = String.format("FMaterialId.FSPECIFICATION like  '%s' and FBASEQTY > 0",itemnumber + "%");
        }

        List<VtuzxMap> bomQuery = vtuzxKingdeeService.query(client, "STK_Inventory", arrayList,
                cond, "FID", 0, 0);
        if(VtuzxUtil.isEmpty(bomQuery)){
            throw new Exception("当前物料没有库存");
        }
        List<VtuzxMap> resList = new ArrayList<>();
        for (VtuzxMap data : bomQuery){
            String fmaterialNo = VtuzxUtil.getString(data,"FMaterialId.FNUMBER");//物料编码
            String fmaterialName = VtuzxUtil.getString(data,"FMaterialId.FName");//物料名称
            Integer forgId = VtuzxUtil.getInt(data,"FStockOrgId.FNumber");//组织编码
            String forgName = VtuzxUtil.getString(data,"FStockOrgId.FNAME");//组织名称
            String batchNo = VtuzxUtil.getString(data,"FLot.fname");//批号
            String stockNo = VtuzxUtil.getString(data,"FStockId.FNUMBER");//仓库编码
            String stockName = VtuzxUtil.getString(data,"FStockName");//仓库名称
            String flot = VtuzxUtil.getString(data,"FLot.fname");//批号
            String fspecification = VtuzxUtil.getString(data,"FMaterialId.FSPECIFICATION");//仓库名称
            double FBASEQTY = VtuzxUtil.getDouble(data,"FBASEQTY");//库存基本数量

            String locationName = VtuzxUtil.getString(data,"FStockLocId.FF100001.FNAME");//获取仓位名称
            String FProduceDate = VtuzxUtil.getString(data,"FProduceDate");//生产日期
            String locationNo = VtuzxUtil.getString(data,"FStockLocId.FF100001.FNUmber");//获取仓位名称
            //返回给后端的数据，现在查询出来的字段信息带.前端无法识别
            VtuzxMap dataMap = new VtuzxMap();
            dataMap.append("fmaterialNo",fmaterialNo)
                    .append("fmaterialName",fmaterialName)
                    .append("forgId",forgId)
                    .append("forgName",forgName)
                    .append("batchNo",batchNo)
                    .append("stockNo",stockNo)
                    .append("stockName",stockName)
                    .append("FBASEQTY",FBASEQTY)
                    .append("locationNo",locationNo)
                    .append("flot",flot)
                    .append("fspecification",fspecification)
                    .append("produceDate",FProduceDate)
                    .append("locationName",locationName);


            resList.add(dataMap);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",resList);

        return data;
    }

    /**
     * 补料传金蝶领料
     * @param userId
     * @param prdFeed
     * @param feedDetailList
     * @throws Exception
     */
    @Override
    public void syncPrdPickByFeed(Long userId, PrdFeed prdFeed, List<PrdFeedDetail> feedDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(userId);
        } catch (Exception e){
            throw new RuntimeException("金蝶账号密码错误请维护");
        }
        Map<String, Object> pickModel = new LinkedHashMap<>();//金蝶领料单model
        pickModel.put("FID",0);//实体主键
        pickModel.put("FBillType",new VtuzxMap("FNUMBER","SCLLD01_SYS"));//单据类型
        pickModel.put("FDate", DateUtils.dateToStr(prdFeed.getFDATE(),"yyyy-MM-dd HH:mm:ss"));//单据日期
        pickModel.put("FStockOrgId",new VtuzxMap("FNUMBER","100"));//发料组织
        pickModel.put("FPrdOrgId",new VtuzxMap("FNUMBER","100"));//生产组织
        pickModel.put("FWorkShopId",new VtuzxMap("FNUMBER","JJ"));//车间默认机加车间
        pickModel.put("FSTOCKERID",new VtuzxMap("FNAME","王英爽"));//仓管员
        pickModel.put("FDescription",prdFeed.getFBillNo());//中台补料单号
        List<Map<String,Object>> FEntity  = new ArrayList<>();//明细信息
        String fbillnomo = prdFeed.getFBILLNOMO();//生产订单号
        SfcProplan sfcProplan = sfcProplanDao.selectOne(new LambdaQueryWrapper<SfcProplan>()
                .eq(SfcProplan::getMoBillNo, fbillnomo));


        for (PrdFeedDetail detail : feedDetailList){
            String materialNo = detail.getFMATERIALNUMBER();
            String materialName = detail.getFMATERIALNAME();
            //查询用料清单编号
            PpBom ppBom = ppBomDao.selectOne(new LambdaQueryWrapper<PpBom>().eq(PpBom::getFMOBILLNO, fbillnomo)
                    .eq(PpBom::getFMATERIALNUMBER,materialNo));
            if (VtuzxUtil.isEmpty(ppBom)){
                throw new RuntimeException(String.format("当前领用件号:%s,不是物料清单件号",detail.getFSPECIFICATION()));
            }
            String ppbomNo = ppBom.getFBILLNO();//用料清单单据编号


            Map<String,Object> entity = new LinkedHashMap<>();//金蝶明细信息
            entity.put("FMaterialId",new VtuzxMap("FNumber",detail.getFMATERIALNUMBER()));//物料编码
            //这个物料编码是订单上的物料编码
            entity.put("FParentMaterialId",new VtuzxMap("FNumber",sfcProplan.getMaterialNo()));//物料编码

//            if (materialName.contains("外协")){
//                entity.put("FStockId",new VtuzxMap("FNumber",detail.getFSTOCKNUMBER()));
//                entity.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber", "998")));//仓位
//            } else {
            entity.put("FStockId",new VtuzxMap("FNumber",detail.getFSTOCKNUMBER()));
            if(detail.getFSTOCKNUMBER().equals("CK005")){
                entity.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber", "998")));//仓位
            }
//            }


            entity.put("FMoBillNo",fbillnomo);//生产订单编号
            entity.put("FPPBomBillNo",ppbomNo);//用料清单编号
            entity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型
            entity.put("FAppQty",detail.getFACTUALQTY());//申请数量
            entity.put("FActualQty",detail.getFACTUALQTY());//实发数量
            entity.put("FStockActualQty",detail.getFACTUALQTY());//主库存单位实发数量
            entity.put("FBaseActualQty",detail.getFACTUALQTY());//基本单位实发数量
            entity.put("FBaseStockActualQty",detail.getFACTUALQTY());//基本单位实发数量
            entity.put("FEntryWorkShopId",new VtuzxMap("FNumber","JJ"));//车间
            entity.put("FUnitID",new VtuzxMap("FNumber",detail.getFUNITID()));//基本单位
//            String trayno = detail.getTRAYNO();//托号
//            Tray tray = trayDao.selectOne(new LambdaQueryWrapper<Tray>()
//                    .eq(Tray::getFBILLNO, trayno));
//            Date instocktime = tray.getINSTOCKTIME();
//             DateUtils.dateToStr(instocktime,"YYYY-MM-DD");
            entity.put("FLot",new Document("FNumber",detail.getFLOT()));//批号


            entity.put("FBaseUnitId",new VtuzxMap("FNumber",detail.getFUNITID()));//基本单位
            //查询库存辅助单位
            String FStockUnitId = "";
            List<VtuzxMap> unitQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FAuxUnitID.fnumber"
                    ),
                    String.format("FNUMBER = '%s'",detail.getFMATERIALNUMBER() ), null, 0, 1);
            if (!VtuzxUtil.isEmpty(unitQuery)) {
                FStockUnitId = VtuzxUtil.getString(unitQuery.get(0),"FAuxUnitID.fnumber");//辅助单位
            }
            entity.put("FStockUnitId",new VtuzxMap("FNumber",detail.getFUNITID()));//库存单位
            entity.put("FSecUnitId",new VtuzxMap("FNumber",FStockUnitId));//辅助单位


            entity.put("FOwnerId",new VtuzxMap("FNumber","100"));//货主
            entity.put("FParentOwnerTypeId","BD_OwnerOrg");//产品货主类型
            entity.put("FParentOwnerId",new VtuzxMap("FNumber","100"));//产品货主

            //查询用料清单获取
            String FId = "";//原单内码
            String FEntryId = "";//分录内码
            //查询原单内码和分录内码
            List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "PRD_PPBOM", new VtuzxArrayList<>(
                            "FId",
                            "FEntity_FEntryID"//分录内码
                    ),
                    String.format("FBillNo = '%s' and FMaterialId2.FNumber = '%s'", ppbomNo,detail.getFMATERIALNUMBER()), null, 0, 1);
            if (!VtuzxUtil.isEmpty(prdInQuery)) {
                FId = VtuzxUtil.getString(prdInQuery.get(0),"FId");
                FEntryId = VtuzxUtil.getString(prdInQuery.get(0),"FEntity_FEntryID");
            }
            //查询生产订单内码
            String moEntryId = "";
            List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MO", new VtuzxArrayList<>(
                            "FTreeEntity_FEntryID"

                    ),
                    String.format("FBillNo = '%s'", fbillnomo), null, 0, 1);

            if (!VtuzxUtil.isEmpty(moQuery)) {
                moEntryId = VtuzxUtil.getString(moQuery.get(0),"FTreeEntity_FEntryID");//生产订单分录内码
            }
            entity.put("FMoEntryId",moEntryId);//生产订单分录内码
            entity.put("FPPBomEntryId",FEntryId);//用料清单分录内码
            //添加link信息(用料清单关联)
            List<Map<String,Object>> linkList = new ArrayList<>();
            Map<String,Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRuleId","ea808801-aef0-84fd-11f0-830bdaa3b1e8");//下推规则
            //linkMap.put("FEntity_Link_FRuleId","3be192e7-0961-4236-90d2-c7c21263e307");//下推规则
            linkMap.put("FEntity_Link_FSTableName","T_PRD_PPBOMENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBillId",FId);//源单内码
            linkMap.put("FEntity_Link_FSId",FEntryId);// 源单分录内码
            linkList.add(linkMap);
            entity.put("FEntity_Link",linkList);
            FEntity.add(entity);
        }
        pickModel.put("FEntity",FEntity);
        Map<String,Object> param = new HashMap<>();//传单总参
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("InterationFlags", "");
        param.put("IsAutoAdjustField", true);
        param.put("Model", pickModel);
        try {
            List<VtuzxMap> pickList = vtuzxKingdeeService.save(client, "PRD_PickMtrl", param);
            VtuzxMap prdReturnMap = pickList.get(0);
            String number = VtuzxUtil.getString(prdReturnMap, "Number");
            //中台保存金蝶单据编号
//            savePickKingNo(prdPick,number);
            vtuzxKingdeeService.submit(client, "PRD_PickMtrl", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_PickMtrl", "0", number, "STK_InvCheckResult");
        } catch (Exception e){

            throw new CustomException(e.getMessage());
        }
    }

    /**
     *补料传金蝶调拨单
     * @param userId
     * @param prdFeed
     * @param feedDetailList
     * @throws Exception
     */
    @Override
    public void syncAllocationByFeed(Long userId, PrdFeed prdFeed, List<PrdFeedDetail> feedDetailList) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(userId);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> param = new LinkedHashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<Map<String, Object>> stockTransferEntryList = new ArrayList<>();//存放单据体数据
        Map<String, Object> model = new LinkedHashMap<>();
        model.put("FID", 0);//实体主键
        model.put("FBillTypeID",new VtuzxMap("FNUMBER","ZJDB01_SYS"));//单据类型r
        model.put("FBizType","NORMAL");//业务类型
        model.put("FTransferDirect","GENERAL");//调拨方向
        model.put("FTransferBizType","InnerOrgTransfer");//调拨类型
        model.put("FSettleOrgId", new VtuzxMap("FNumber","100"));//结算组织
        model.put("FSaleOrgId",new VtuzxMap("FNumber","100"));//销售组织
        model.put("FStockOutOrgId",new VtuzxMap("FNumber","100"));//调出库存组织
        model.put("FOwnerTypeOutIdHead", "BD_OwnerOrg");//调出货主类型
        model.put("FOwnerOutIdHead",new VtuzxMap("FNumber","100"));//调出货主
        model.put("FStockOrgId",new VtuzxMap("FNumber","100"));//调入库存组织
        model.put("FIsIncludedTax",true);//是否含税
        model.put("FIsPriceExcludeTax",true);//价外税
        model.put("FExchangeTypeId",new VtuzxMap("FNUMBER","HLTX01_SYS"));//汇率类型
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//调入货主类型
        model.put("FSETTLECURRID", new VtuzxMap("FNumber", "PRE001"));
        model.put("FExchangeRate", 1.0);
        model.put("FOwnerIdHead", new VtuzxMap("FNumber", "100"));
        model.put("FDate", sdf.format(prdFeed.getFDATE()));
        model.put("FBaseCurrId", new VtuzxMap("FNumber", "PRE001"));
        model.put("FWriteOffConsign",false);//冲减普通寄售调拔单结算数量
        model.put("FNOTE",prdFeed.getFBillNo());//备注

        //单据体数据
        for (PrdFeedDetail feedDetail : feedDetailList){
            String materialNo  = feedDetail.getFMATERIALNUMBER();

            //判断是否启用批号,查询辅助单位
            String floatCond = String.format("FNumber = '%s'", materialNo);
            List<VtuzxMap> bd_Material = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                    "FIsBatchManage",
                    "FBaseUnitId",
                    "FAuxUnitID.fnumber"//辅助单位
            ), floatCond);
            boolean FIsBatchManage = true;//是否启用批号

            String FAuxUnitID = "";
            if (bd_Material != null && bd_Material.size() > 0) {
                FIsBatchManage = bd_Material.get(0).getBoolean("FIsBatchManage");
                FAuxUnitID = bd_Material.get(0).getString("FAuxUnitID.fnumber");
            }


            Map<String, Object> stockTransferEntry = new LinkedHashMap<>();
            stockTransferEntry.put("FMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FUnitID", new VtuzxMap("FNumber", feedDetail.getFUNITID()));
            stockTransferEntry.put("FQty", feedDetail.getFACTUALQTY());//数量
            String batchNo = "";
            stockTransferEntry.put("FLot", new VtuzxMap("FNumber", feedDetail.getFLOT()));
            stockTransferEntry.put("FSrcStockId", new VtuzxMap("FNumber", "CK002"));//调出仓库是砂芯库
            stockTransferEntry.put("FDestStockId", new VtuzxMap("FNumber", "CK018"));//调入仓库是铸造材料库
            stockTransferEntry.put("FSrcStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FDestStockStatusId", new VtuzxMap("FNumber", "KCZT01_SYS"));
            stockTransferEntry.put("FBusinessDate", VtuzxUtil.formatYmdHmsF(new Date()));
            stockTransferEntry.put("FOwnerTypeOutId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FOwnerTypeId", "BD_OwnerOrg");
            stockTransferEntry.put("FOwnerId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FSecUnitId", new VtuzxMap("FNumber", FAuxUnitID));//库存辅助单位
            stockTransferEntry.put("FBaseUnitId", new VtuzxMap("FNumber", feedDetail.getFUNITID()));
            stockTransferEntry.put("FBaseQty", feedDetail.getFACTUALQTY());
            stockTransferEntry.put("FISFREE", false);
            stockTransferEntry.put("FKeeperTypeId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FKeeperTypeOutId", "BD_KeeperOrg");
            stockTransferEntry.put("FKeeperOutId", new VtuzxMap("FNumber", "100"));
            stockTransferEntry.put("FDestLot", new VtuzxMap("FNumber", feedDetail.getFLOT()));
            stockTransferEntry.put("FDestMaterialId", new VtuzxMap("FNumber", materialNo));
            stockTransferEntry.put("FSaleUnitId", new VtuzxMap("FNumber", feedDetail.getFUNITID()));
//            stockTransferEntry.put("FPriceUnitID", new VtuzxMap("FNumber", pickDetail.getFUNITID()));
            stockTransferEntry.put("FTransReserveLink", false);
            stockTransferEntry.put("FCheckDelivery", false);
            stockTransferEntryList.add(stockTransferEntry);


        }
        model.put("FBillEntry",stockTransferEntryList);
        param.put("NeedUpDateFields", new ArrayList<>());
        param.put("NeedReturnFields", new ArrayList<>());
        param.put("IsDeleteEntry", true);
        param.put("SubSystemId", "");
        param.put("IsVerifyBaseDataField", false);
        param.put("IsEntryBatchFill", true);
        param.put("ValidateFlag", true);
        param.put("NumberSearch", true);
        param.put("IsAutoAdjustField",false);
        param.put("InterationFlags", "");
        param.put("IgnoreInterationFlag","");
        param.put("IsControlPrecision",false);
        param.put("ValidateRepeatJson",false);
        param.put("Model", model);
        try {
            List<VtuzxMap> transferList = vtuzxKingdeeService.save(client, "STK_TransferDirect", param);
            VtuzxMap transferMap = transferList.get(0);
            String number = VtuzxUtil.getString(transferMap, "Number");
            vtuzxKingdeeService.submit(client, "STK_TransferDirect", "0", number);
            vtuzxKingdeeService.audit(client, "STK_TransferDirect", "0", number, "STK_InvCheckResult");
//

        } catch (Exception e){
            _logger.info(e.getMessage());
        }
    }

    /**
     * pda端传金蝶采购入库
     * @param user_id
     * @param userName
     * @param map
     * @throws Exception
     */
    @Override
    public void syncPurInOrderByPda(Long user_id, String userName, Map<String, Object> map) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请维护");
        }

        String receiveBillNo = VtuzxUtil.getString(map,"receiveBillNo");
        String billNo = VtuzxUtil.getString(map,"billNo");//收料单号
        PurIn purIn = purInDao.selectOne(new LambdaQueryWrapper<PurIn>()
                .eq(PurIn::getBillNo, billNo));

        Map<String, Object> model = new LinkedHashMap<>();//采购入库api总参
        //根据收料通知单号查询金蝶fid和fentryid,用于linked采购入库单
        Receive receive = receiveDao.selectOne(new LambdaQueryWrapper<Receive>()
                .eq(Receive::getBillNo, receiveBillNo));
        //查询收料通知单号获取结算方式结算币别等信息
        Map<String, Object> receiveMap = recceiveQuery(client, receiveBillNo);
        String settleMode = VtuzxUtil.getString(receiveMap, "settleMode");//结算方式
        String FSettleCurrId = VtuzxUtil.getString(receiveMap, "FSettleCurrId");//结算币别
        String FPayConditionId = VtuzxUtil.getString(receiveMap, "FPayConditionId");//付款条件
        String FPurDeptId = VtuzxUtil.getString(receiveMap, "FPurDeptId");//采购部门
        String FPurchaserId = VtuzxUtil.getString(receiveMap, "FPurchaserId");//采购员
        Double FExchangeRate = VtuzxUtil.getDouble(receiveMap, "FExchangeRate");//汇率

        List<Map<String, Object>> FInStockEntry = new ArrayList<>();//采购入库体数据

        String materialNo = VtuzxUtil.getString(map,"materialNo");
        String unitNo = VtuzxUtil.getString(map,"unitNo");
        String flot = VtuzxUtil.getString(map,"flot");
        String stockNo = VtuzxUtil.getString(map,"stockNo");
        String locationNo = VtuzxUtil.getString(map,"locationNo");
        Double mustQty = VtuzxUtil.getDouble(map,"mustQty");//应收数量
        Double realQty = VtuzxUtil.getDouble(map,"realQty");//实收数量
        int reveiveId = VtuzxUtil.getInt(map,"reveiveId");//收料详情id
        Receivedetail receivedetail = receivedetailDao.selectById(reveiveId);


        Boolean isLocation = VtuzxUtil.getBoolean(map,"isLocation");//是否启用仓位
        //查询物料是否有辅助单位
        String auxNo = checkFAux(materialNo, client);


        Map<String, Object> colMap = new LinkedHashMap<>();
        colMap.put("FRowType", "Standard");//产品类型
        colMap.put("FMaterialId", new Document("FNumber", materialNo));//物料编码
        colMap.put("FUnitID", new Document("FNumber",unitNo));//物料单位
        if (!VtuzxUtil.isEmpty(auxNo)) {
            colMap.put("FAuxUnitID", new Document("FNumber", auxNo));//辅助单位
        }
        colMap.put("FPOOrderNo", receive.getPurOrderNo());//订单单号，通过linked方式无法获取，直接传
        colMap.put("FMustQty", mustQty);//实收数量
        colMap.put("FRealQty", realQty);//实收数量
        colMap.put("FPriceUnitID", new Document("FNumber", unitNo));//计价单位
        colMap.put("FLot", new Document("FNumber", flot));//批号
        colMap.put("FStockId", new Document("FNumber", stockNo));//仓库
        if (isLocation) {
            colMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber", locationNo)));//仓位
        }
        colMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
//        colMap.put("FTaxPrice", receivedetail1.getFPrice());//含税单价
        colMap.put("FGiveAway", false);//是否正品
        colMap.put("FOWNERTYPEID", "BD_OwnerOrg");//货主类型
        colMap.put("FCheckInComing", false);//来料校验
        colMap.put("FIsReceiveUpdateStock", false);//收料后更新库存状态
        colMap.put("FPriceBaseQty",realQty);//计价基本数量
        colMap.put("FRemainInStockUnitId", new Document("FNumber", unitNo));//采购单位
        colMap.put("FBILLINGCLOSE", false);//立账关闭
        colMap.put("FRemainInStockQty", realQty);//采购数量
        colMap.put("FAPNotJoinQty", realQty);//未关联应付数量（计价单位
        colMap.put("FRemainInStockBaseQty", realQty);//采购基本数量
        colMap.put("FOWNERID", new Document("FNumber", "100"));//货主
        colMap.put("FSRCBILLTYPEID", "PUR_ReceiveBill");//原单类型
        colMap.put("FSRCBillNo", receiveBillNo);//原单类型
        //添加linked信息(收料通知单关联)
        List<Map<String, Object>> linkList = new ArrayList<>();
        Map<String, Object> linkMap = new LinkedHashMap<>();
        linkMap.put("FInStockEntry_Link_FRULEID", "PUR_ReceiveBill-STK_InStock");//下推规则
        linkMap.put("FInStockEntry_Link_FSTABLENAME", "T_PUR_ReceiveEntry");//关联表名
        linkMap.put("FInStockEntry_Link_FSBILLID", receive.getFID());//源单内码，同步收料通知单时将fid和fentryid同步到中台
        linkMap.put("FInStockEntry_Link_FSID", receivedetail.getFEntryId());// 源单分录内码
        linkList.add(linkMap);
        colMap.put("FInStockEntry_Link", linkList);
        FInStockEntry.add(colMap);


        model.put("FID", 0);//实体主键
        model.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型标准采购入库单
        model.put("FSettleTypeId", new Document("FNUMBER", settleMode));//结算方式

        model.put("FDate", DateUtils.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));//入库日期

        model.put("FStockOrgId", new Document("FNumber", "100"));//收料组织
        model.put("FDemandOrgId", new Document("FNumber", "100"));//需求组织
        model.put("FPurchaseOrgId", new Document("FNumber", "100"));//采购组织
        model.put("FSupplierId", new Document("FNumber", purIn.getSupplierNo()));//供应商
        model.put("FPurchaseDeptId", new Document("FNumber", FPurDeptId));//采购部门
        model.put("FPurchaserId", new Document("FNumber", FPurchaserId));//采购员
        model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        model.put("FOwnerIdHead", new Document("FNumber", "100"));//货主
        model.put("F_VKFP_lljyd", purIn.getInspectBillNo());//来料检验单号
        model.put("F_PSUH_TEXT_9Z6", purIn.getBillNo());//中台采购入库单号

        Document FInStockFin = new Document();
        FInStockFin.append("FSettleOrgId", new Document("FSettleOrgId", new Document("FNumber", "100")));
        FInStockFin.append("FSettleCurrId", new Document("FNumber", FSettleCurrId));//结算币别
        FInStockFin.append("FPayConditionId", new Document("FNumber", FPayConditionId));//付款条件
        FInStockFin.append("FExchangeRate", FExchangeRate);
        model.put("FInStockFin", FInStockFin);//财务信息
        model.put("FExchangeTypeId", new Document("FNumber", "HLTX01_SYS"));//汇率类型
        model.put("FInStockEntry", FInStockEntry);

        Map<String, Object> kneeParam = new LinkedHashMap<>();
        kneeParam.put("NeedUpDateFields", new ArrayList<>());
        kneeParam.put("NeedReturnFields", new ArrayList<>());
        kneeParam.put("IsDeleteEntry", true);
        kneeParam.put("SubSystemId", "");
        kneeParam.put("IsVerifyBaseDataField", true);
        kneeParam.put("IsEntryBatchFill", false);
        kneeParam.put("ValidateFlag", true);
        kneeParam.put("NumberSearch", true);
        kneeParam.put("InterationFlags", "");
        kneeParam.put("Model", model);
        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "STK_InStock", kneeParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "STK_InStock", "0", number);
            vtuzxKingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            _logger.info(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }




    }

    /**
     * 铸造的废料入到回材库
     * @param user_id
     * @param prdInstock
     * @param detailList
     * @param failCount
     */
    @Override
    public void syncPrdInsStockHuiCaiSM(Long user_id, PrdInstock prdInstock, List<PrdInstockDetail> detailList, Double failCount) throws Exception {
        //通过工序汇报单下推生产入库，然后保存入库单
        //报废数量需要通过单据编号下推，要不然有数量校验无法保存入库
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //根据汇报单号查询金蝶汇报单用于下推(汇报单号存在金蝶明细中的备注)
        String reportNo = prdInstock.getREPORTNO();//中台汇报单号

        String floatCond = String.format("FDescription = '%s'", reportNo);
        List<VtuzxMap> planList = vtuzxKingdeeService.query(client, "SFC_OperationReport", new VtuzxArrayList<>(
                "FEntity_FENTRYID",//末序汇报entryid
                "FBILLNO"
        ), floatCond);
        String FBILLNO = "";//末序汇报entryid
        if (!VtuzxUtil.isEmpty(planList)){
            FBILLNO = VtuzxUtil.getString(planList.get(0),"FBILLNO");
        }
        //工序计划下推工序汇报

        Map<String, Object> model = new LinkedHashMap<>();
        model.put("Ids", "");
        model.put("Numbers",FBILLNO);//单据编码集合
        model.put("EntryIds", "");//分录内码
        model.put("RuleId", "SFC_OPTRPT2INSTOCK");//转换规则内码
//        model.put("RuleId", "1f4f462d-8810-4a5d-ae9d-5a684200abfc");//转换规则内码
        model.put("TargetBillTypeId", "");
        model.put("TargetOrgId", 0);
        model.put("IsEnableDefaultRule", false);
        model.put("IsDraftWhenSaveFail", false);
        model.put("CustomParams", new VtuzxMap());

        //工序汇报单下推生产入库单
        List<VtuzxMap> optrptList = vtuzxKingdeeService.push(client, "SFC_OperationReport", model);
        VtuzxMap optrpt = optrptList.get(0);
        String optrptNo = VtuzxUtil.getString(optrpt,"Number");//下推后的入库单号
        String optrptiD = VtuzxUtil.getString(optrpt,"Id");//下推后的入库单id
        LinkedHashMap entryIdList = VtuzxUtil.getObject(optrpt,"EntryIds");

        List<Integer> idList = (List<Integer>) entryIdList.get("FEntity");
        Integer optEntryId = idList.get(0);//entryId

        //修改刚才下推的单据
        Map<String, Object> updateParam = new LinkedHashMap<>();//传单总参
        Map<String, Object> updateModle = new LinkedHashMap<>();//传单nodel
        updateModle.put("FID", optrptiD);
        updateModle.put("FBillNo", optrptNo);
        updateModle.put("FDATE", DateUtils.dateToStr(prdInstock.getFDATE(),"yyyy-MM-dd HH:mm:ss"));
        updateModle.put("FDescription", prdInstock.getFBillNo());//备注暂时存中台生产入库单号

        List<Map<String, Object>> FEntity = new ArrayList<>();//存放单据体数据

        Map<String, Object> entryMap = new LinkedHashMap<>();

        entryMap.put("FENTRYID",optEntryId);//实体主键
        entryMap.put("FRealQty",failCount);//实收数量
        entryMap.put("FStockId",new Document("FNUMBER","CK023"));//实收数量
        FEntity.add(entryMap);

        updateModle.put("FEntity",FEntity);
        updateParam.put("NeedUpDateFields", new ArrayList<>());
        updateParam.put("NeedReturnFields", new ArrayList<>());
        updateParam.put("IsDeleteEntry", true);
        updateParam.put("SubSystemId", "");
        updateParam.put("IsVerifyBaseDataField", true);
        updateParam.put("IsEntryBatchFill", false);
        updateParam.put("ValidateFlag", true);
        updateParam.put("NumberSearch", true);
        updateParam.put("InterationFlags", "");
        updateParam.put("Model", updateModle);
        try {
            vtuzxKingdeeService.save(client, "PRD_INSTOCK", updateParam);
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", optrptNo);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", optrptNo, "STK_InvCheckResult");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 销售订单
     *
     * @param qingSaleOrder
     * @param qingSaleOrderDetailList
     * @throws Exception
     */
    @Override
    public void syncQingSaleOrder(QingSaleOrder qingSaleOrder, List<QingSaleOrderDetail> qingSaleOrderDetailList, Map<String, Object> materialToMap, Map<String, Object> customerMap, Map<String, Object> acccusMap, Map<String, Object> currencyMap, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头
        //查询客户编码
//        String cusNo = getCusNo(saleOrder.getCusTomer());
        String cusNo = VtuzxUtil.getString(customerMap, qingSaleOrder.getCusTomer());
        System.out.println("终端客户原始值: " + qingSaleOrder.getCusTomer());
        String accusNo = VtuzxUtil.getString(acccusMap, qingSaleOrder.getAccCustomer());
        //单据头
        saleModel.put("FID", 0);
        saleModel.put("FBillTypeID", new Document("FNUMBER", "XSDD01_SYS"));
        saleModel.put("FSaleDeptId", new Document("FNUMBER", "BM000006"));//销售部门
        saleModel.put("FSalerId", new Document("FNUMBER", "0153_GW000006_1"));//销售员
        saleModel.put("FCustId", new Document("FNumber", accusNo));//结算客户
        saleModel.put("F_PSUH_Base_qtr", new Document("FNumber", cusNo));//终端客户
        saleModel.put("FDate", DateUtils.dateToStr(qingSaleOrder.getInDate(), "yyyy-MM-dd HH:mm:ss"));
        saleModel.put("FSaleOrgId", new Document("FNumber", "100"));
        saleModel.put("F_PSUH_Text_qtr", qingSaleOrder.getCusBillNo());//客户订单号
        saleModel.put("FNote", qingSaleOrder.getNote());

        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息
        //查询币别的编码
        String currency = qingSaleOrder.getCurrency();//币别
        String currentyNo = VtuzxUtil.getString(currencyMap, currency);
        if (VtuzxUtil.isEmpty(currentyNo)) {
            throw new RuntimeException(String.format("金蝶不存在币别'%s'", currency));
        }

        double FExchangeRate = 1.0;
        //如果是人民币的话不用查税率
        if (!"人民币".equals(currency)) {
            //根据原币查询汇率
            List<VtuzxMap> tateQuery = vtuzxKingdeeService.query(client, "BD_Rate", new VtuzxArrayList<>(
                            "FExchangeRate"
                    ),
                    String.format("FCyForID.fnumber = '%s'", currentyNo), null, 0, 0);
            if (!VtuzxUtil.isEmpty(tateQuery)) {
                FExchangeRate = VtuzxUtil.getDouble(tateQuery.get(0), "FExchangeRate");
            } else {
                throw new RuntimeException(String.format("金蝶不存在原币为'%s'的汇率", currency));
            }
        }
        saleFIn.put("FSettleCurrId", new Document("FNumber", currentyNo));//结算币别
        saleFIn.put("FExchangeRate", FExchangeRate);//汇率
        saleModel.put("FSaleOrderFinance", saleFIn);

        //订单明细
        List<Map<String, Object>> FSaleOrderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (QingSaleOrderDetail detail : qingSaleOrderDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            String maNo = detail.getMaterialNo();//ty件号
            entryMap.put("FRowType", "Standard");
            Map<String, Object> materialMap = VtuzxUtil.getObject(materialToMap, maNo);
            String unitNo = "";
            if (!VtuzxUtil.isEmpty(materialMap)) {
                unitNo = VtuzxUtil.getString(materialMap, "unitNo");

            }

            entryMap.put("FMATERIALID", new Document("FNumber", maNo));//物料编码
            entryMap.put("FUnitID", new Document("FNumber", unitNo));//单位
            entryMap.put("Fqty", detail.getQty());//销售数量
            entryMap.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
            entryMap.put("FTaxPrice", detail.getTaxPrice());//含税单价
            entryMap.put("FEntryTaxRate", detail.getTaxRate());//税率
            entryMap.put("F_VKFP_Text_qtr", detail.getCwLot());//储位/批号
            entryMap.put("FIsFree", detail.getIsGift());//是否为赠品
            entryMap.put("F_PSUH_Date_ca9", DateUtils.dateToStr(detail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
            FSaleOrderEntry.add(entryMap);

        }
        saleModel.put("FSaleOrderEntry", FSaleOrderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);


        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "SAL_SaleOrder", saleParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "SAL_SaleOrder", "0", number);
            vtuzxKingdeeService.audit(client, "SAL_SaleOrder", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 销售订单变更
     *
     * @param qingSaleOrder
     * @param saleqingOrderDetailList
     * @throws Exception
     */
    @Override
    public void syncqingSaleUpdateOrder(QingSaleOrder qingSaleOrder, List<QingSaleOrderDetail> saleqingOrderDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        String cusBillNo = qingSaleOrder.getCusBillNo();//客户订单号
        Map<String, Object> kingdeeqingSaleOrder = getKingdeeqingSaleOrder(cusBillNo, user_id);
        VtuzxMap orderParam = new VtuzxMap();
        VtuzxMap orderArgs = new VtuzxMap();
        orderArgs.append("SaleOrderBillNo", VtuzxUtil.getString(kingdeeqingSaleOrder, "billNo"));
        orderArgs.append("SaleOrderBillId", VtuzxUtil.getString(kingdeeqingSaleOrder, "fid"));
        orderArgs.append("SOEntryIds", VtuzxUtil.getObject(kingdeeqingSaleOrder, "entryList"));
        orderParam.append("saveXSaleOrderArgs", orderArgs);
        List<Map<String, Object>> customerList = new ArrayList<>();
        //查询币别的编码
        String currency = qingSaleOrder.getCurrency();//币别
        String currentyNo = "";
        //根据ty件号(对应金蝶物料编码)查询单位编码
        List<VtuzxMap> currenQuery = vtuzxKingdeeService.query(client, "BD_Currency", new VtuzxArrayList<>(
                        "FNumber"
                ),
                String.format("FName = '%s'", currency), null, 0, 0);
        if (!VtuzxUtil.isEmpty(currenQuery)) {
            currentyNo = VtuzxUtil.getString(currenQuery.get(0), "FNumber");
        } else {
            throw new RuntimeException(String.format("金蝶不存在币别'%s'", currency));
        }
        try {
            //先调用销售订单变更单
            customerList = vtuzxKingdeeService.orderUp(client, "SAL_XORDER", orderArgs);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        Map<String, Object> matMap = new HashMap<>();//key:物料id，val:单价
        Map<String, Object> detailMap = new HashMap<>();//key:物料内码，val:订单详情
        for (QingSaleOrderDetail detail : saleqingOrderDetailList) {
            String MaterialNo = detail.getMaterialNo();//客户件号
            Double taxPrice = detail.getTaxPrice();
            String FMATERIALID = "";
            //根据物料件号(编码)查询内码
            List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                            "FMATERIALID"
                    ),
                    String.format("FNumber = '%s'", MaterialNo), null, 0, 0);
            if (!VtuzxUtil.isEmpty(prdInQuery)) {
                FMATERIALID = VtuzxUtil.getString(prdInQuery.get(0), "FMATERIALID");
            } else {
                throw new RuntimeException(String.format("金蝶不存在物料:%s", MaterialNo));
            }
            matMap.put(FMATERIALID, taxPrice);
            detailMap.put(FMATERIALID, detail);

        }
        List<Map<String, Object>> entryList = VtuzxUtil.getObject(customerList.get(0), "SaleOrderEntry");//变更单返回的明细
        String fid = VtuzxUtil.getString(customerList.get(0), "FID");//单据头id
        Map<String, Object> kingEntryMap = new HashMap<>();//key:物料内码 val;金蝶单据体内码
        for (Map<String, Object> entryMap : entryList) {
            String materialId = VtuzxUtil.getString(entryMap, "FMaterialId");
            String entryId = VtuzxUtil.getString(entryMap, "FEntryID");
            kingEntryMap.put(materialId, entryId);
        }

        List<Map<String, Object>> orderEntryList = new ArrayList<>();//需要保存的单据体数据
        //循环订单明细添加变更单信息(FChangeType变更类型D删除，A修改，B新增)
        for (Map.Entry entry : detailMap.entrySet()) {
            String materialId = (String) entry.getKey();//物料内码
            QingSaleOrderDetail orderDetail = (QingSaleOrderDetail) entry.getValue();//详情数据
            String type = orderDetail.getType();
            //新增的话不需要entryid
            if ("新增".equals(type)) {
                Map<String, Object> kingdeeEntry = new LinkedHashMap<>();
                String Material = orderDetail.getMaterialNo();//ty件号
                kingdeeEntry.put("FRowType", "Standard");
                String unitNo = "";
                String materialNo = "";
                //根据ty件号(对应金蝶物料编码)查询单位编码
                List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FBaseUnitId.fnumber",
                                "FNumber"
                        ),
                        String.format("FNumber = '%s'", Material), null, 0, 0);
                if (!VtuzxUtil.isEmpty(prdInQuery)) {
                    unitNo = VtuzxUtil.getString(prdInQuery.get(0), "FBaseUnitId.fnumber");
                    materialNo = VtuzxUtil.getString(prdInQuery.get(0), "FNumber");
                } else {
                    throw new RuntimeException(String.format("金蝶不存在物料%s", Material));
                }
                kingdeeEntry.put("FMATERIALID", new Document("FNumber", materialNo));//物料编码
                kingdeeEntry.put("FUnitID", new Document("FNumber", unitNo));//单位
                kingdeeEntry.put("Fqty", orderDetail.getQty());//销售数量
                kingdeeEntry.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
                kingdeeEntry.put("FTaxPrice", orderDetail.getTaxPrice());//含税单价
                kingdeeEntry.put("F_VKFP_Text_qtr", orderDetail.getCwLot());//储位/批号
                kingdeeEntry.put("FEntryTaxRate", orderDetail.getTaxRate());//税率
                kingdeeEntry.put("FIsFree", orderDetail.getIsGift());//是否为赠品
                kingdeeEntry.put("F_PSUH_Date_ca9", DateUtils.dateToStr(orderDetail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
                kingdeeEntry.put("FChangeType", "A");
                orderEntryList.add(kingdeeEntry);
            } else if ("删除".equals(type)) {
                String entryId = VtuzxUtil.getString(kingEntryMap, materialId);//详情内码
                Map<String, Object> kingdeeEntry = new LinkedHashMap<>();
                kingdeeEntry.put("FEntryId", entryId);
                kingdeeEntry.put("FChangeType", "D");
                orderEntryList.add(kingdeeEntry);
            } else {//修改
                String entryId = VtuzxUtil.getString(kingEntryMap, materialId);//详情内码
                Map<String, Object> kingdeeEntry = new LinkedHashMap<>();
                String Material = orderDetail.getMaterialNo();//ty件号
                kingdeeEntry.put("FRowType", "Standard");
                kingdeeEntry.put("FEntryId", entryId);
                String unitNo = "";
                String materialNo = "";
                //根据ty件号(对应金蝶物料编码)查询单位编码
                List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                                "FBaseUnitId.fnumber",
                                "FNumber"
                        ),
                        String.format("FNumber = '%s'", Material), null, 0, 0);
                if (!VtuzxUtil.isEmpty(prdInQuery)) {
                    unitNo = VtuzxUtil.getString(prdInQuery.get(0), "FBaseUnitId.fnumber");
                    materialNo = VtuzxUtil.getString(prdInQuery.get(0), "FNumber");
                } else {
                    throw new RuntimeException(String.format("金蝶不存在物料%s", Material));
                }
                kingdeeEntry.put("FMATERIALID", new Document("FNumber", materialNo));//物料编码
                kingdeeEntry.put("FUnitID", new Document("FNumber", unitNo));//单位
                kingdeeEntry.put("Fqty", orderDetail.getQty());//销售数量
                kingdeeEntry.put("FPriceUnitId", new Document("FNumber", unitNo));//计价单位
                kingdeeEntry.put("F_VKFP_Text_qtr", orderDetail.getCwLot());//储位/批号
                kingdeeEntry.put("FTaxPrice", orderDetail.getTaxPrice());//含税单价
                kingdeeEntry.put("FEntryTaxRate", orderDetail.getTaxRate());//税率
                kingdeeEntry.put("FIsFree", orderDetail.getIsGift());//是否为赠品
                kingdeeEntry.put("F_PSUH_Date_ca9", DateUtils.dateToStr(orderDetail.getShipDate(), "yyyy-MM-dd HH:mm:ss"));//船期
                kingdeeEntry.put("FChangeType", "B");
                orderEntryList.add(kingdeeEntry);
            }
        }


        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头

        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息

        saleFIn.put("FSettleCurrId", new Document("FNumber", currentyNo));//结算币别
        saleModel.put("FSaleOrderFinance", saleFIn);

        saleModel.put("FID", fid);
        saleModel.put("FSaleOrderEntry", orderEntryList);
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("Model", saleModel);
        try {
//            // 创建 Gson 实例并启用格式化
//            Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
//            // 将 saleParam 转换为格式化的 JSON
//            String json = gson.toJson(saleParam);
//            System.out.println("JSON 输出:\n" + json);
            List<VtuzxMap> sal_xorder = vtuzxKingdeeService.save(client, "SAL_XORDER", saleParam);
            VtuzxMap kingdeeCustomerMap = sal_xorder.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "SAL_XORDER", "0", number);
            vtuzxKingdeeService.audit(client, "SAL_XORDER", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public void syncQingPrdOrder(QingSfcOperp qingSfcOperp, List<QingSfcOperpDetail> qingsfcOperpDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> qingsfcParam = new LinkedHashMap<>();//传单param
        Map<String, Object> qingsfcModel = new LinkedHashMap<>();//单据头
        //查询单据类型
        String typeNo = getOrderType(qingSfcOperp.getType(), client);
        //单据头
        qingsfcModel.put("FBillNo", qingSfcOperp.getMoBillNo());//单据编号
        qingsfcModel.put("FDescription", qingSfcOperp.getRemark());//备注
        qingsfcModel.put("FBillType", new Document("FNUMBER", typeNo));//单据类型
        qingsfcModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        qingsfcModel.put("FDate", DateUtils.dateToStr(qingSfcOperp.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));//单据日期
        qingsfcModel.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
        qingsfcModel.put("FPPBOMType", 1);//用料清单展开
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (QingSfcOperpDetail detail : qingsfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();

            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FUnitId", new Document("FNumber", detail.getUnitNo()));//单位
            entryMap.put("FWorkShopID", new Document("FNumber", detail.getDepartNo()));//生产车间
            //TODO 产品类型
            entryMap.put("Fqty", detail.getQty());//数量
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanStart(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间

            orderEntry.add(entryMap);

        }
        qingsfcModel.put("FTreeEntity", orderEntry);
        qingsfcParam.put("NeedUpDateFields", new ArrayList<>());
        qingsfcParam.put("NeedReturnFields", new ArrayList<>());
        qingsfcParam.put("IsDeleteEntry", true);
        qingsfcParam.put("SubSystemId", "");
        qingsfcParam.put("IsVerifyBaseDataField", false);
        qingsfcParam.put("IsEntryBatchFill", true);
        qingsfcParam.put("ValidateFlag", true);
        qingsfcParam.put("NumberSearch", true);
        qingsfcParam.put("InterationFlags", "");
        qingsfcParam.put("Model", qingsfcModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_MO", qingsfcParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_MO", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_MO", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void syncQingPrdOrderUpdate(QingSfcOperp qingSfcOperp, List<QingSfcOperpDetail> qingsfcOperpDetailList, Long user_id, Map<String, Object> countMap) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        //查询出订单fid和entryid,还有订单的数量(防止没有在中台做变更没传过去)
        String fid = "";
        String entryId = "";
        double orderCount = 0.0;
        String FConveyDate = "";//变更单的日期为生产订单的下达日期
        List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MO", new VtuzxArrayList<>(
                        "FID",
                        "FQty",
                        "FTreeEntity_FEntryId",
                        "FConveyDate"//下达日期
                ),
                String.format("FBillNo = '%s'", qingSfcOperp.getMoBillNo()), null, 0, 0);
        if (!VtuzxUtil.isEmpty(moQuery)) {
            fid = VtuzxUtil.getString(moQuery.get(0), "FID");
            entryId = VtuzxUtil.getString(moQuery.get(0), "FTreeEntity_FEntryId");
            orderCount = VtuzxUtil.getDouble(moQuery.get(0), "FQty");
            FConveyDate = VtuzxUtil.getString(moQuery.get(0), "FConveyDate");
        } else {
            throw new RuntimeException(String.format("金蝶不存在订单编号为:%s的订单", qingSfcOperp.getMoBillNo()));
        }

        //判断变更单是否上传过(保存状态的不让重复传，审核的可以传)
        List<VtuzxMap> moUpdateQuery = vtuzxKingdeeService.query(client, "PRD_MOChange", new VtuzxArrayList<>(
                        "FBillNo"
                ),
                String.format("FMoId = '%s' and FMoEntryId = '%s' and  FDocumentStatus != 'C' ", fid, entryId), null, 0, 0);
        if (!VtuzxUtil.isEmpty(moUpdateQuery)) {
            throw new RuntimeException(String.format("订单编号为:%s的订单已经上传过变更单,单据编号为:%s", qingSfcOperp.getMoBillNo(), VtuzxUtil.getString(moUpdateQuery.get(0), "FBillNo")));
        }

        Map<String, Object> saleParam = new LinkedHashMap<>();//传单param
        Map<String, Object> saleModel = new LinkedHashMap<>();//单据头

        //TODO 校验数量变更数量不能小于领料+ 补料 - 退料(根据用料清单中的已领数量判断，找发料方式，是直接领料的)
        Double pickedQty = 0.0;//已领数量
        List<VtuzxMap> ppbomQuery = vtuzxKingdeeService.query(client, "PRD_PPBOM", new VtuzxArrayList<>(
                        "FPickedQty",//已领数量
                        "FBillNo"
                ),
                String.format("FMOBILLNO = '%s' and FIssueType = '1'", qingSfcOperp.getMoBillNo()), null, 0, 0);
        if (!VtuzxUtil.isEmpty(ppbomQuery)) {
            pickedQty = VtuzxUtil.getDouble(ppbomQuery.get(0), "FPickedQty");
        }
        Double count = VtuzxUtil.getDouble(countMap, qingSfcOperp.getMoBillNo() + "_" + qingsfcOperpDetailList.get(0).getMaterialNo());
        if (count == 0) {
            throw new RuntimeException(String.format("订单编号:%s中的物料信息与原订单物料信息不一致,请确认", qingSfcOperp.getMoBillNo()));
        }
        if (count < pickedQty) {
            throw new RuntimeException("变更数量不能小于已领数量");
        }
        //单据头
        saleModel.put("FBillType", new Document("FNUMBER", "SCDDBGD01_SYS"));//单据类型
        saleModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        saleModel.put("FDescription", qingSfcOperp.getRemark());//备注
        saleModel.put("FDate", FConveyDate);//单据日期为生产订单的下达日期
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        //添加明细信息
        for (QingSfcOperpDetail detail : qingsfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FChangeType", "2");//变更类型
            entryMap.put("FProductType", "1");//产品类型
            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FMoNo", qingSfcOperp.getMoBillNo());//生产订单编号
            entryMap.put("FMoEntrySeq", 1);//生产订单行号
            entryMap.put("FUnitId", new Document("FNumber", detail.getUnitNo()));//单位
            entryMap.put("FQty", orderCount);//数量
            entryMap.put("FStatus", "2");//业务状态
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanStart(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间
            entryMap.put("FMoId", fid);//生产订单内码
            entryMap.put("FMoEntryId", entryId);//生产订单分录内码

            entryMap.put("FStockInOrgId", new Document("FNumber", "100"));//入库组织
            entryMap.put("FReqType", "1");//需求类型1
            entryMap.put("FSrcBillType", "PRD_MO");//源单类型
            entryMap.put("FSrcBillNo", detail.getBillNo());//源单编号
            entryMap.put("FSrcBillId", fid);//源单内码
            entryMap.put("FSrcBillEntryId", entryId);//源单分录内码
            entryMap.put("FSrcBillEntrySeq", 1);//源单行好
            //添加linked信息(关联生产订单)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRULEID", "PRD_MO2MOCHANGE");//下推规则
            linkMap.put("FEntity_Link_FSTABLENAME", "T_PRD_MOENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBILLID", fid);//源单内码
            linkMap.put("FEntity_Link_FSID", entryId);// 源单分录内码
            linkMap.put("FEntity_Link_FBaseQtyOld", orderCount);// 原始携带量
            linkMap.put("FEntity_Link_FBaseQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//修改携带量
            linkList.add(linkMap);
            entryMap.put("FEntity_Link", linkList);

            orderEntry.add(entryMap);

        }
        //变更后
        for (QingSfcOperpDetail detail : qingsfcOperpDetailList) {
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FChangeType", "3");//变更类型
            entryMap.put("FProductType", "1");//产品类型
            entryMap.put("FMATERIALID", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FMoNo", qingSfcOperp.getMoBillNo());//生产订单编号
            entryMap.put("FMoEntrySeq", 1);//生产订单行号
            entryMap.put("FUnitId", new Document("FNumber", detail.getUnitNo()));//单位
            entryMap.put("FQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//数量
            entryMap.put("FStatus", "2");//业务状态
            entryMap.put("FPlanFinishDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划完工时间
            entryMap.put("FPlanStartDate", DateUtils.dateToStr(detail.getPlanEnd(), "yyyy-MM-dd HH:mm:ss"));//计划开工时间
            entryMap.put("FMoId", fid);//生产订单内码
            entryMap.put("FMoEntryId", entryId);//生产订单分录内码

            entryMap.put("FStockInOrgId", new Document("FNumber", "100"));//入库组织
            entryMap.put("FReqType", "1");//需求类型1
            entryMap.put("FSrcBillType", "PRD_MO");//源单类型
            entryMap.put("FSrcBillNo", detail.getBillNo());//源单编号
            entryMap.put("FSrcBillId", fid);//源单内码
            entryMap.put("FSrcBillEntryId", entryId);//源单分录内码
            entryMap.put("FSrcBillEntrySeq", 2);//源单分录行
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();
            linkMap.put("FEntity_Link_FRULEID", "PRD_MO2MOCHANGE");//下推规则
            linkMap.put("FEntity_Link_FSTABLENAME", "T_PRD_MOENTRY");//关联表名
            linkMap.put("FEntity_Link_FSBILLID", fid);//源单内码
            linkMap.put("FEntity_Link_FSID", entryId);// 源单分录内码
            linkMap.put("FEntity_Link_FBaseQtyOld", orderCount);// 原始携带量
            linkMap.put("FEntity_Link_FBaseQty", VtuzxUtil.getDouble(countMap, detail.getBillNo() + "_" + detail.getMaterialNo()));//修改携带量
            linkList.add(linkMap);
            entryMap.put("FEntity_Link", linkList);
            orderEntry.add(entryMap);

        }
        saleModel.put("FEntity", orderEntry);
        saleParam.put("NeedUpDateFields", new ArrayList<>());
        saleParam.put("NeedReturnFields", new ArrayList<>());
        saleParam.put("IsDeleteEntry", true);
        saleParam.put("SubSystemId", "");
        saleParam.put("IsVerifyBaseDataField", false);
        saleParam.put("IsEntryBatchFill", true);
        saleParam.put("ValidateFlag", true);
        saleParam.put("NumberSearch", true);
        saleParam.put("InterationFlags", "");
        saleParam.put("Model", saleModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_MOChange", saleParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_MOChange", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_MOChange", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void syncQingPrdInstock(QingSfcInstock qingSfcInstock, List<QingSfcInstockDetail> qingSfcInstockDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }


        Map<String, Object> qingsfcParam = new LinkedHashMap<>();//传单param
        Map<String, Object> qingsfcModel = new LinkedHashMap<>();//单据头
        // 使用 IdentityHashMap 来保留重复的明细
        Map<QingSfcInstockDetail, Double> remainingQtyMap = new IdentityHashMap<>();
        for (QingSfcInstockDetail detail : qingSfcInstockDetailList) {
            remainingQtyMap.put(detail, detail.getQty()); // 初始化为原始数量
        }

        //查询单据类型
        String typeNo = getOrderType(qingSfcInstock.getType(), client);
        //单据头
//        qingsfcModel.put("FBillNo",qingSfcInstock.getMoBillNo());//单据编号
        qingsfcModel.put("FBillType", new Document("FNUMBER", typeNo));//单据类型
        qingsfcModel.put("FPrdOrgId", new Document("FNUMBER", "100"));//生产组织
        qingsfcModel.put("FStockOrgId", new Document("FNUMBER", "100"));//生产组织
        qingsfcModel.put("FDate", DateUtils.dateToStr(qingSfcInstock.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));//单据日期
        qingsfcModel.put("FOwnerTypeId0", "BD_OwnerOrg");//货主类型
        qingsfcModel.put("FOwnerId0", new Document("FNUMBER", "100"));//货主类型
        qingsfcModel.put("FOwnerTypeId", "BD_OwnerOrg");//货主类型
        //订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        // 创建一个对象来存储查询结果，而不是使用 List<String>
        List<VtuzxMap> moQuery = vtuzxKingdeeService.query(client, "PRD_MORPT",
                new VtuzxArrayList<>("FID", "FEntity_FEntryID","FQuaQty","FMoId","FMoEntryId","FWorkshipId.FNumber"),
                String.format("FMoBillNo = '%s' and FStockInSelQty - FQuaQty <>0", qingSfcInstock.getMoBillNo()),
                null, 0, 0);

        if (!VtuzxUtil.isEmpty(moQuery)) {
            // 循环处理查询结果
            for (VtuzxMap result : moQuery) {
                // 分别获取 FID 和 FTreeEntity_FEntryId 和已分配数量
                String fid = VtuzxUtil.getString(result, "FID");
                String entryId = VtuzxUtil.getString(result, "FEntity_FEntryID");
                String FMoId = VtuzxUtil.getString(result, "FMoId");
                String FMoEntryId = VtuzxUtil.getString(result, "FMoEntryId");
                String FWorkshipId = VtuzxUtil.getString(result, "FWorkshipId.FNumber");
                Double moQty = VtuzxUtil.getDouble(result, "FQuaQty");
                double allocatedQty = 0.0; // 已分配数量
                // 遍历入库明细列表
                Iterator<QingSfcInstockDetail> iterator = qingSfcInstockDetailList.iterator();
                while (iterator.hasNext() && allocatedQty < moQty) {
                    QingSfcInstockDetail detail = iterator.next();

                    // 获取剩余数量
                    double remainingQty = remainingQtyMap.get(detail);

                    // 跳过已完全使用的明细
                    if (remainingQty <= 0) {
                        continue;
                    }

                    // 计算本次可以使用的数量
                    double qtyToUse;
                    if (allocatedQty + remainingQty <= moQty) {
                        qtyToUse = remainingQty;
                    } else {
                        qtyToUse = moQty - allocatedQty;
                    }

                    // 更新已分配数量和剩余数量
                    allocatedQty += qtyToUse;
                    remainingQtyMap.put(detail, remainingQty - qtyToUse);

                    // 创建entryMap
                    Map<String, Object> entryMap = new LinkedHashMap<>();
                    String stockNo = "";

                    // 根据仓库名称查询仓库编码
                    List<VtuzxMap> prdInQuery = vtuzxKingdeeService.query(client, "BD_STOCK",
                            new VtuzxArrayList<>("FNumber"),
                            String.format("FName  = '%s'", detail.getStock()), null, 0, 0);

                    if (!VtuzxUtil.isEmpty(prdInQuery)) {
                        stockNo = VtuzxUtil.getString(prdInQuery.get(0), "FNumber");
                    } else {
                        throw new RuntimeException(String.format("金蝶不存在仓库%s", detail.getStock()));
                    }
                    entryMap.put("FInStockType", "1");//入库类型
                    entryMap.put("FIsNew", false);//是否新增行
                    entryMap.put("FProductType", "1");//主产品
                    entryMap.put("FMoId", FMoId );//生产订单内码
                    entryMap.put("FMoEntryId",  FMoEntryId);//生产订单分录内码
                    entryMap.put("FMoEntrySeq",  1);//生产订单分录内码 //
                    entryMap.put("FMOMAINENTRYID",FMoEntryId);//生产订单主产品分录内码
                    entryMap.put("FSrcEntryId", entryId);//原单分录内码
                    entryMap.put("FMaterialId", new Document("FNumber", detail.getMaterialNo()));//物料编码
                    entryMap.put("FUnitID", new Document("FNumber", detail.getUnitNo()));//单位
                    entryMap.put("FMustQty",  qtyToUse);//应收数量
                    entryMap.put("FRealQty", qtyToUse);//实收说
                    entryMap.put("FOwnerTypeId",  "BD_OwnerOrg");//库存状态
                    entryMap.put("FLot", new Document("FNumber", detail.getLot()));//单位
                    entryMap.put("FOwnerId", new Document("FNumber", "100"));//保管者
                    entryMap.put("FStockId", new Document("FNumber", stockNo));//仓库
                    entryMap.put("FStockLocId", new Document("FSTOCKLOCID__FF100001", new Document("FNumber",detail.getLocation())));//仓位
                    entryMap.put("FWorkShopId1", new Document("FNumber", FWorkshipId));//生产车间
                    entryMap.put("FKeeperId", new Document("FNumber", "100"));//保管者
                    entryMap.put("FMoBillNo", detail.getBillNo());//生产订单号
                    entryMap.put("FStockStatusId", new Document("FNumber", "KCZT01_SYS"));//库存状态
                    entryMap.put("FKeeperTypeId", "BD_KeeperOrg");//保管者类型
                    entryMap.put("FMemo",detail.getRemark());//备注

                    List<Map<String, Object>> linkList = new ArrayList<>();
                    Map<String, Object> linkMap = new LinkedHashMap<>();
                    linkMap.put("FEntity_Link_FRULEID", "PRD_MO2MOCHANGE");//下推规则
                    linkMap.put("FEntity_Link_FSTABLENAME", "T_PRD_MORPTENTRY");//关联表名
                    linkMap.put("FEntity_Link_FSBILLID", fid);  // 源单内码
                    linkMap.put("FEntity_Link_FSID", entryId);  // 源单分录内码
                    linkList.add(linkMap);
                    entryMap.put("FEntity_Link", linkList);

                    orderEntry.add(entryMap);

                    // 如果明细已完全使用，从列表中移除
                    if (remainingQty - qtyToUse <= 0) {
                        iterator.remove();
                    }
                }
            }
        } else {
            throw new RuntimeException(String.format("未查询到生产汇报单: %s", qingSfcInstock.getMoBillNo()));
        }
        qingsfcModel.put("FEntity", orderEntry);
        qingsfcParam.put("NeedUpDateFields", new ArrayList<>());
        qingsfcParam.put("NeedReturnFields", new ArrayList<>());
        qingsfcParam.put("IsDeleteEntry", true);
        qingsfcParam.put("SubSystemId", "");
        qingsfcParam.put("IsVerifyBaseDataField", false);
        qingsfcParam.put("IsEntryBatchFill", false);
        qingsfcParam.put("ValidateFlag", true);
        qingsfcParam.put("NumberSearch", true);
        qingsfcParam.put("InterationFlags", "");
        qingsfcParam.put("Model", qingsfcModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "PRD_INSTOCK", qingsfcParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            vtuzxKingdeeService.submit(client, "PRD_INSTOCK", "0", number);
            vtuzxKingdeeService.audit(client, "PRD_INSTOCK", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void syncQingPurIn(QingPurIn qingPurIn, List<QingPurInDetail> qingPurInDetailList, Long user_id) throws Exception {
        VtuzxKingdeeCloudClient client = null;
        try {
            client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
        } catch (Exception e) {
            throw new RuntimeException("金蝶账号密码错误，请在中台修改自己的金蝶账号或密码");
        }
        Map<String, Object> qingpurinParam = new LinkedHashMap<>();//传单param
        Map<String, Object> qingpurinModel = new LinkedHashMap<>();//单据头
        String CustomerNo = "";
        String CurrencyNo = "";
        String FID = "";
        String FEntityID = "";
        String stockNo= "";
        String FTaxPrice="";
        String FEntryTaxRate = "";
        String FPrice= "";
        Double FRemainStockINQty= 0.0;
        //单据头
//        qingpurinModel.put("FBillNo", qingPurIn.getPurBillNo());//单据编号
        qingpurinModel.put("FBillTypeID", new Document("FNUMBER", "RKD01_SYS"));//单据类型
        qingpurinModel.put("FStockOrgId", new Document("FNUMBER", "100"));//收料组织
        qingpurinModel.put("FDate", DateUtils.dateToStr(qingPurIn.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));//单据日期
        qingpurinModel.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型
        qingpurinModel.put("FOwnerIdHead", new Document("FNUMBER", "100"));//货主
        qingpurinModel.put("FPurchaseOrgId", new Document("FNUMBER", "100"));//采购组织
        qingpurinModel.put("FBusinessType", "CG");//业务类型
        qingpurinModel.put("F_VKFP_Remarks",qingPurIn.getRemark());


        //根据供应商名
        List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client, "PUR_PurchaseOrder", new VtuzxArrayList<>(
                        "FSupplierId.FNumber","FSettleCurrId.FNumber"
                ),

                String.format("FBillNo = '%s' ",
                        qingPurIn.getPurBillNo()), null, 0, 0);
        if (!VtuzxUtil.isEmpty(prdcumQuery)) {
            CustomerNo = VtuzxUtil.getString(prdcumQuery.get(0), "FSupplierId.FNumber");
            CurrencyNo = VtuzxUtil.getString(prdcumQuery.get(0), "FSettleCurrId.FNumber");
        } else {
            throw new RuntimeException(String.format("单据不存在%s", qingPurIn.getPurBillNo()));
        }
        qingpurinModel.put("FSupplierId", new Document("FNUMBER", CustomerNo));//供应商

        Map<String, Object> saleFIn = new LinkedHashMap<>();//财务信息
        saleFIn.put("FSettleOrgId", new Document("FNumber", "100"));//结算币别

        saleFIn.put("FSettleCurrId", new Document("FNumber", CurrencyNo));//结算币别
        saleFIn.put("FPriceTimePoint", "1");//定价时点
        qingpurinModel.put("FInStockFin", saleFIn);
        // 订单明细
        List<Map<String, Object>> orderEntry = new ArrayList<>();//明细信息
        for (QingPurInDetail detail : qingPurInDetailList) {
            //根据订单号和物料编码查询FID和FEntityId
            List<VtuzxMap> purinlinkid = vtuzxKingdeeService.query(client, "PUR_PurchaseOrder", new VtuzxArrayList<>(
                            "FID","FPOOrderEntry_FEntryID","FTaxPrice","FEntryTaxRate","FPrice"
                    ),

                    String.format("FBillNo = '%s'  and FMaterialId.FNumber = '%s' ",
                            qingPurIn.getPurBillNo(),detail.getMaterialNo()), null, 0, 0);
            if (!VtuzxUtil.isEmpty(purinlinkid)) {
                FID = VtuzxUtil.getString(purinlinkid.get(0), "FID");
                FEntityID = VtuzxUtil.getString(purinlinkid.get(0), "FPOOrderEntry_FEntryID");
                FTaxPrice = VtuzxUtil.getString(purinlinkid.get(0), "FTaxPrice");
                FEntryTaxRate = VtuzxUtil.getString(purinlinkid.get(0), "FEntryTaxRate");
                FPrice = VtuzxUtil.getString(purinlinkid.get(0), "FPrice");
            } else {
                throw new RuntimeException(String.format("单据不存在%s", qingPurIn.getPurBillNo()));
            }
            //判断数量是否符合
            List<VtuzxMap> purincount = vtuzxKingdeeService.query(client, "PUR_PurchaseOrder", new VtuzxArrayList<>(
                            "FRemainStockINQty"
                    ),

                    String.format("FBillNo = '%s'  and FMaterialId.FNumber = '%s' ",
                            qingPurIn.getPurBillNo(),detail.getMaterialNo()), null, 0, 0);
            if (!VtuzxUtil.isEmpty(purinlinkid)) {
                FRemainStockINQty = VtuzxUtil.getDouble(purincount.get(0), "FRemainStockINQty");
                if(FRemainStockINQty < detail.getQty()){
                    throw new RuntimeException(String.format("采购订单%s剩余入库数量小于本次入库数量", qingPurIn.getPurBillNo()));
                }
            } else {
                throw new RuntimeException(String.format("单据不存在%s", qingPurIn.getPurBillNo()));
            }

            List<VtuzxMap> prdMoBillNoQuery = vtuzxKingdeeService.query(client, "BD_STOCK",
                    new VtuzxArrayList<>("FNumber"),
                    String.format("FName  = '%s'", detail.getStock()), null, 0, 0);

            if (!VtuzxUtil.isEmpty(prdMoBillNoQuery)) {
                stockNo = VtuzxUtil.getString(prdMoBillNoQuery.get(0), "FNumber");
            } else {
                throw new RuntimeException(String.format("金蝶不存在仓库%s", detail.getStock()));
            }
            Map<String, Object> entryMap = new LinkedHashMap<>();
            entryMap.put("FMaterialId", new Document("FNumber", detail.getMaterialNo()));//物料编码
//            entryMap.put("FMaterialId", new Document("FNumber", detail.getMaterialNo()));//物料编码
            entryMap.put("FRealQty", detail.getQty());//数量
            entryMap.put("FPriceBaseQty", detail.getQty());//计价基本数量
            entryMap.put("F_VKFP_Text_83g", detail.getMoBillNo());//生产订单编号
            entryMap.put("FUnitID",new Document("FNumber",detail.getUnitNo()));//库存单位
            entryMap.put("FPriceUnitID",new Document("FNumber",detail.getUnitNo()));//计价单位
            entryMap.put("FStockId",new Document("FNumber",stockNo));//仓库
            entryMap.put("FStockStatusId",new Document("FNumber","KCZT01_SYS"));//仓库状态
            entryMap.put("FStockLocId",new Document("FSTOCKLOCID__FF100002",new Document("FNumber",detail.getLocation())));//仓位
            entryMap.put("FTaxPrice", FTaxPrice);//含税单价
            entryMap.put("FEntryTaxRate", FEntryTaxRate);//税率
            entryMap.put("FPrice", FPrice);//单价
            entryMap.put("FRemainInStockUnitId",new Document("FNumber",detail.getUnitNo()));//计价单位
            entryMap.put("FLot",new Document("FNumber",detail.getLot()));//库存单位
            entryMap.put("FOWNERID", new Document("FNUMBER", "100"));//货主
            entryMap.put("FSRCBillNo", qingPurIn.getPurBillNo());//单据编号
            entryMap.put("Fnote",detail.getRemark());//备注
            entryMap.put("FPOOrderNo",detail.getPurBillNo());//采购订单单号
            entryMap.put("FPOORDERENTRYID",FEntityID);//采购订单分录

            //添加linked信息(收料通知单关联)
            List<Map<String, Object>> linkList = new ArrayList<>();
            Map<String, Object> linkMap = new LinkedHashMap<>();

            linkMap.put("FInStockEntry_Link_FRuleId", "PUR_PurchaseOrder-STK_InStock");//下推规则
            linkMap.put("FInStockEntry_Link_FSTableName", "t_PUR_POOrderEntry");//关联表名
            linkMap.put("FInStockEntry_Link_FSBillId", FID);//源单内码，同步收料通知单时将fid和fentryid同步到中台
            linkMap.put("FInStockEntry_Link_FSId", FEntityID);// 源单分录内码
            linkList.add(linkMap);
            entryMap.put("FInStockEntry_Link", linkList);

            orderEntry.add(entryMap);

        }
        qingpurinModel.put("FInStockEntry", orderEntry);
        qingpurinParam.put("NeedUpDateFields", new ArrayList<>());
        qingpurinParam.put("NeedReturnFields", new ArrayList<>());
        qingpurinParam.put("IsDeleteEntry", true);
        qingpurinParam.put("SubSystemId", "");
        qingpurinParam.put("IsVerifyBaseDataField", false);
        qingpurinParam.put("IsEntryBatchFill", false);
        qingpurinParam.put("IsAutoAdjustField", true);
        qingpurinParam.put("ValidateFlag", true);
        qingpurinParam.put("NumberSearch", true);
        qingpurinParam.put("InterationFlags", "");
        qingpurinParam.put("Model", qingpurinModel);

        try {
            List<VtuzxMap> customerList = vtuzxKingdeeService.save(client, "STK_InStock", qingpurinParam);
            VtuzxMap kingdeeCustomerMap = customerList.get(0);
            String number = VtuzxUtil.getString(kingdeeCustomerMap, "Number");
            qingPurIn.setId(qingPurIn.getId());
            qingPurIn.setRkBillNo(number);
            // 插入主单据并获取ID
            qingPurInDao.updateRkBillNo(qingPurIn);
//            vtuzxKingdeeService.submit(client, "STK_InStock", "0", number);
//            vtuzxKingdeeService.audit(client, "STK_InStock", "0", number, "STK_InvCheckResult");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }


    }


}



















